![](/img/trans.png)
[英]How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?
[英]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
指的是與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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.