首页 > 解决方案 > 有没有办法使用泛型类型别名作为 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>>()
}

标签: genericsrust

解决方案


不,因为 Rust 不对类型别名强制类型边界。您的示例等效于:

type DebuggableFromStr<T> = T;

游乐场

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


推荐阅读