我如何为另一个泛型类型的特征绑定表达类型参数的特征绑定?

How can I express a trait bound on a type parameter for another generic type's trait bound?

我正在尝试改进一些现有代码,通过添加类型变量代替具体类型来使其更通用。

原始代码如下所示:

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 指的是与 TFromStr 实现关联的类型参数,但我如何表达这种类型——我实际上并不知道——具有Display 特征?

最初这很令人困惑,因为我不明白它指的是哪个 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()
}