簡體   English   中英

如何在另一個泛型類型的特征綁定的類型參數上表達特征?

[英]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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM