I am trying to call a generic static method within a different static method, but I get a confusing error:
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`
When I ran rustc --explain E0283
, the error message said:
This error occurs when the compiler doesn't have enough information to unambiguously choose an implementation.
Which is confusing as there is only one implementation of the function.
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;
}
}
It means Rust couldn't figure out the type of T
. Rust generic methods work by generating a separate implementation for each concrete T
that you actually use in your code. Meaning you need a concrete type spelled out somewhere.
You could fix it by using something like:
return Config::parse_json(source, datatype as AConcreteDataType);
But to know the problem for sure, we'd need to see the rest of the calling code in main.rs
.
Aside from that, the parse_json
method looks iffy; why is it returning the datatype
instead of the decoded
result?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With