[英]is there a way to use a generic type alias as the generic type for a function in Rust
I want to be able to reuse a generic type alias as the generic type parameter for a couple of functions in Rust.我希望能够重用泛型类型别名作为 Rust 中几个函数的泛型类型参数。
I have tried creating the following type alias following the syntax specified in the type alias rust docs :我尝试按照类型别名 rust docs 中指定的语法创建以下类型别名:
type DebuggableFromStr<T: FromStr>
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
= T;
and would like to use it to replace the generic type definitions in the following function:并希望使用它来替换以下函数中的泛型类型定义:
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>>()
}
Nope since Rust doesn't enforce type bounds on type aliases.不,因为 Rust 不强制类型别名的类型边界。 Your example is equivalent to this:
你的例子相当于:
type DebuggableFromStr<T> = T;
Playground . 游乐场。
I don't believe it to be specifically documented anywhere but the compiler issues a warning if you try.我不相信它会在任何地方专门记录,但是如果您尝试,编译器会发出警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.