如何在调用泛型静态方法时解决“所需的类型注释:无法解析_”?

时间:2016-08-23 14:41:35

标签: generics rust

我试图在不同的静态方法中调用泛型静态方法,但是我遇到了一个令人困惑的错误:

error: type annotations required: cannot resolve `_: Config` [--explain E0283]
  --> src/main.rs:15:38
   |>
15 |>                     "json" => return Config::parse_json::<T>(source, datatype),
   |>                                      ^^^^^^^^^^^^^^^^^^^^^^^
note: required by `Config::parse_json`

当我运行rustc --explain E0283时,错误消息显示:

  

当编译器没有足够的信息时会发生此错误   毫不含糊地选择实施。

这是令人困惑的,因为只有一个函数的实现。

use rustc_serialize::json;
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use rustc_serialize;

pub trait Config {
    fn get_config<T: rustc_serialize::Decodable>(source: PathBuf, datatype: T) -> Option<T> {
        let extension = source.extension().unwrap();
        if let Some(extension) = extension.to_str() {
            match extension {
                "json" => return Config::parse_json::<T>(source, datatype),
                _ => panic!("Unable to parse the specfied extension."),
            }
        } else {
            panic!("No extension was found.");
        }
    }

    fn parse_json<T: rustc_serialize::Decodable>(source: PathBuf, datatype: T) -> Option<T> {
        let mut file = File::open(source).unwrap();
        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();
        let decoded: T = json::decode(&contents).unwrap();
        let option: Option<T> = Some(datatype);
        return option;
    }
}

1 个答案:

答案 0 :(得分:0)

这意味着Rust无法找出T的类型。 Rust泛型方法通过为您在代码中实际使用的每个具体T生成单独的实现来工作。意思是你需要在某处拼出一个具体的类型。

您可以使用以下内容修复它:

return Config::parse_json(source, datatype as AConcreteDataType);

但要确定问题,我们需要在main.rs中看到其余的调用代码。

除此之外,parse_json方法看起来不确定;为什么返回datatype而不是decoded结果?