Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Debug for generic types in Rust

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading