gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:59:00 25 4
gpt4 key购买 nike

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

原始代码如下所示:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com