gpt4 book ai didi

generics - 调用泛型静态方法时如何解析 "type annotations required: cannot resolve _"?

转载 作者:行者123 更新时间:2023-11-29 07:48:56 24 4
gpt4 key购买 nike

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

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 时,错误消息说:

This error occurs when the compiler doesn't have enough information to unambiguously choose an implementation.

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

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

最佳答案

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

您可以使用类似的方法修复它:

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

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

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

关于generics - 调用泛型静态方法时如何解析 "type annotations required: cannot resolve _"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com