I am learning rust and I wanted to make a small helper lib to parse a file and cast the content as Vec<T>
. My idea is to use it like that: file_to_vec::<u32>("path/to/file")
I was doing that for now:
use std::fmt::Debug;
use std::str::FromStr;
use std::fs::{read_to_string};
pub fn file_to_vec<T>(path: &str) -> Vec<T> where T: FromStr {
return read_to_string(path)
.expect("Error reading input")
.trim()
.split("\n")
.map(|line| line.parse::<T>().unwrap())
.collect();
}
The compiler is saying:
<T as FromStr>::Err cannot be formatted using {:?} because it doesn't implement Debug
I will have to implement it but I don’t know how.
impl<T> fmt::Debug {
???
}
I tried to read the documentation Here but it was not helping
>Solution :
The problem is that unwrap()
requires the error type to implement Debug
because it prints it if an error occurred.
The solution is to require the error type to be Debug
. The error type is <T as FromStr>::Err
or simply T::Err
, so:
pub fn file_to_vec<T>(path: &str) -> Vec<T>
where
T: FromStr,
T::Err: Debug,
{
return read_to_string(path)
.expect("Error reading input")
.trim()
.split("\n")
.map(|line| line.parse::<T>().unwrap())
.collect();
}