【问题标题】:How to resolve "type annotations required: cannot resolve _" when calling generic static method?调用通用静态方法时如何解决“需要类型注释:无法解析_”?
【发布时间】:2016-08-23 14:41:34
【问题描述】:

我试图在不同的静态方法中调用通用静态方法,但我得到一个令人困惑的错误:

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;
    }
}

【问题讨论】:

  • 您没有在任何地方使用selfSelf;为什么这些功能在一个特征中?错误可能是没有 nothing 将方法与实现类型联系起来。
  • 我不需要 self 做它是一个静态方法,但你是对的,不被某些东西所暗示......显然我需要更多的咖啡。不过还是谢谢。

标签: generics rust


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-25
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多