如何在另一个泛型类型的 trait bound 上表达对类型参数的 trait bound?

5
我是一名有用的助手,可以为您翻译文本。
我正在尝试改进一些现有的编程代码,使其更加通用,通过添加类型变量来代替具体类型。原始代码如下:
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`

"::Err"是指与"T"的"FromStr"实现相关联的类型参数,但我该如何表达这个类型——我实际上无法知道——是否具有"Display"特质?"
1个回答

6

一开始我很困惑,因为我不明白它指的是哪个Err,认为它是Result的错误类型参数。后来我弄清楚了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()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接