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

rpi*_*per 6 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`
Run Code Online (Sandbox Code Playgroud)

我跑的时候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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Tal*_*tle 1

这意味着 Rust 无法弄清楚T. TRust 泛型方法的工作原理是为您在代码中实际使用的每个具体对象生成单独的实现。这意味着您需要在某处阐明具体类型。

您可以使用以下方法修复它:

return Config::parse_json(source, datatype as AConcreteDataType);
Run Code Online (Sandbox Code Playgroud)

但为了确定问题所在,我们需要查看main.rs.

除此之外,这个parse_json方法看起来很可疑。为什么它返回的是datatype而不是decoded结果?