我正在尝试改进一些现有的代码,通过添加一个类型变量来代替一个具体的类型,使它变得更通用。
原始代码如下所示:
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
特性呢?
发布于 2015-11-29 06:57:43
这一开始让人感到困惑,因为我不知道它指的是哪个错误--我以为它是Result
的Err
类型参数。一旦我发现FromStr
有它自己的Err
类型参数,我就必须弄清楚如何表达这个约束。这就是它:
fn parse_row<T>(text: String) -> Result<Vec<T>, String>
where
T: Copy + Debug + FromStr,
T::Err: Display,
{
text.split(" ")
.map(|s| s.to_owned()
.parse::<T>()
.map_err(|e| e.to_string())
)
.collect()
}
https://stackoverflow.com/questions/33976810
复制相似问题