我正在尝试改进一些现有的代码,通过添加一个类型变量来代替一个具体的类型,使它变得更通用。
原始代码如下所示:
fn parse_row(text: String) -> Result<Vec<u32>, String> {
text.split(" ")
.map(|s| s.to_owned()
.parse::<u32>()
.map_err(|e| e.to_string())
)
.collect()
}
下面是通用版本:
fn parse_row<T>(text: String) -> Result<Vec<T>, String>
where
T: Copy + Debug + FromStr + Display,
{
text.split(" ")
.map(|s| s.to_owned()
.parse::<T>()
.map_err(|e| e.to_string())
)
.collect()
}
我得到的错误是:
error[E0599]: no method named `to_string` found for type `<T as std::str::FromStr>::Err` in the current scope
--> src/main.rs:7:28
|
7 | .map_err(|e| e.to_string())
| ^^^^^^^^^
|
= note: the method `to_string` exists but the following trait bounds were not satisfied:
`<T as std::str::FromStr>::Err : std::string::ToString`
<T as core::str::FromStr>::Err
引用的是与T
的FromStr
实现相关的类型参数,但是我如何表示这个类型--我实际上不知道--具有Display
特性呢?
https://stackoverflow.com/questions/33976810
复制相似问题