[英]How can I express a trait bound on a type parameter for another generic type's trait bound?
I'm trying to improve some existing code I to make it more generic, by adding a type variable in place of a concrete type. 我正在尝试通过添加一个类型变量来代替具体类型来改进现有的一些代码,使其更通用。
The original code looked like this: 原始代码如下所示:
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()
}
And here is the generic version: 这是通用版本:
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()
}
The error I get is: 我得到的错误是:
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
is referring to the type parameter associated with T
's FromStr
implementation, but how can I express that this type — that I can't actually know — has the Display
trait? <T as core::str::FromStr>::Err
指的是与T
的FromStr
实现相关的类型参数,但是我如何表达这种类型 - 我实际上无法知道 - 具有Display
特征?
This was confusing initially because I didn't understand which Err
it was referring to - and thought it was the error type parameter for Result
. 这最初令人困惑,因为我不明白它指的是哪个
Err
- 并且认为它是Result
的错误类型参数。 Once I figured out that FromStr
has its own Err
type parameter, I just had to work out how to express that constraint. 一旦我发现
FromStr
有自己的Err
类型参数,我只需要弄清楚如何表达这个约束。 And here it is: 这是:
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.