Rust中泛型的调试

  • 本文关键字:调试 泛型 Rust rust
  • 更新时间 :
  • 英文 :


我正在学习rust,我想做一个小的助手库来解析文件并将内容转换为Vec<T>。我的想法是这样使用它:file_to_vec::<u32>("path/to/file")

我现在正在做这件事:

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

编译器说:<T as FromStr>::Err cannot be formatted using {:?} because it doesn't implement Debug

我将不得不实现它,但我不知道如何。

impl<T> fmt::Debug {
???
}

我试着阅读这里的文档,但它没有帮助

问题是unwrap()需要错误类型来实现Debug,因为如果发生错误,它会打印它。

解决方案是要求错误类型为Debug。错误类型是<T as FromStr>::Err或简单的T::Err,所以:

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

最新更新