generics - 有没有办法使用泛型类型别名作为 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;
游乐场。
我不相信它会在任何地方专门记录,但如果您尝试,编译器会发出警告。
推荐阅读
- asp.net-mvc - 如何在 mvc 中为日期设置初始值?
- powerbi - 根据过滤器选择更改矩阵的列名
- ios - Airplay 不能与 Swift 的 AVRoutePicker 一起使用,但可以与 Objective C 一起使用
- r - 使用完整的 NA 填充组,使其长度与最大组相同
- linux - 使用 Qt 创建的 AppImage 和带有 gtk3 插件的 linuxdeployqt 无法在 Gnome 4 上启动
- sql - 将sql中的数据格式化为一行
- python - urlunparse 与 urlparse 不一致
- javascript - 如何使用 JavaScript 在 HTML 表格中显示 JSON 数据
- sql-server - SSIS 读取没有列名的文件
- css - 是否可以在 CSS 网格列中获取固定对象?