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

标签 generics rust traits

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

原始代码如下所示:

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特质?

最佳答案

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

关于generics - 我如何为另一个泛型类型的特征绑定(bind)表达类型参数的特征绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976810/

相关文章:

ios - 通用功能在同一环境中表现不同

带闭包的 Swift 泛型函数

Java F-Bound 通过接口(interface)绑定(bind)

rust - 为什么不能在同一结构中存储值和对该值的引用?

c++ - 还检查继承函数的函数签名

rust - 如何为我不拥有的类型实现我不拥有的特征?

c# - 通用静态字段初始化

rust - 防 rust 罩概念

rust - 如何在 Rust 中读写文本文件?

rust - 有没有办法实现具有不同签名的特征方法?