有没有一种方法可以使用通用类型别名作为Rust中函数的通用类型

时间:2020-01-03 22:46:46

标签: generics rust

我希望能够将通用类型别名用作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>>()
}

1 个答案:

答案 0 :(得分:1)

不会,因为Rust不会对类型别名强制执行类型限制。您的示例与此等效:

type DebuggableFromStr<T> = T;

Playground

我不认为它会在任何地方专门记录,但是如果您尝试编译器会发出警告。