[英]is there a way to use a generic type alias as the generic type for a function in Rust
我希望能夠重用泛型類型別名作為 Rust 中幾個函數的泛型類型參數。
我嘗試按照類型別名 rust docs 中指定的語法創建以下類型別名:
type DebuggableFromStr<T: FromStr>
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
= T;
並希望使用它來替換以下函數中的泛型類型定義:
fn split_string_to_vec<T: FromStr>(s: String) -> Vec<T>
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
s.split_whitespace()
.map(|s| s.parse().unwrap())
.collect::<Vec<T>>()
}
不,因為 Rust 不強制類型別名的類型邊界。 你的例子相當於:
type DebuggableFromStr<T> = T;
游樂場。
我不相信它會在任何地方專門記錄,但是如果您嘗試,編譯器會發出警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.