我希望能够将通用类型别名作为Rust中几个函数的通用类型参数重用。
我尝试按照type alias 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;
Playground。
我不相信它会被专门记录在任何地方,但是如果您尝试这样做,编译器会发出警告。
关于generics - 有没有一种方法可以使用通用类型别名作为Rust中函数的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586238/