types - 如何匹配泛型参数的具体类型?
问题描述
我有一个带有类型参数的函数,U
它返回一个Option<U>
. U
受 trait 约束num::Num
。因此,U
可以是usize
, u8
, u16
, u32
, u64
, u128
,isize
等。
我该如何搭配U
?例如,
match U {
u8 => {},
u16 => {}
_ => {}
}
解决方案
I assume the reason you'd like to match against a type is because you'd like to have the switching at compile time instead of runtime. Unfortunately Rust does not have that kind of inspection (yet?), but what you could do is create a trait for this which then you can implement for the types you'd like to use:
trait DoSomething {
fn do_something(&self) -> Option<Self>
where
Self: Sized;
}
impl DoSomething for u8 {
fn do_something(&self) -> Option<u8> {
Some(8)
}
}
impl DoSomething for u16 {
fn do_something(&self) -> Option<u16> {
Some(16)
}
}
fn f<U>(x: U) -> Option<U>
where
U: DoSomething,
{
x.do_something()
}
fn main() {
println!("{:?}", f(12u8));
println!("{:?}", f(12u16));
}
推荐阅读
- python - 为什么在尝试使用 selenium webdriver 抓取数据时出现此错误(IndentationError:意外缩进)?
- python - 为什么翻译矩阵不影响python中3d模型的渲染?
- ajax - AWS API 网关确实运行良好,但我无法在 javascript AJAX 上运行它
- java - 通话结束后,TelephonyManager 通话状态仍设置为 CALL_STATE_RINGING
- swift - 如何使用货币 NumberFormatter 格式化负 0
- python - sklearn 线性回归似乎不适合
- java - 重命名由应用程序在 android 10 中创建的 Mediastore 文件。在 Android API 30 上工作,但在 API 29 中显示错误
- mysql - Mysql查询返回每个元素的最新结果
- powershell - 使用 Powershell 压缩文件
- swiftui - 如何在 SwiftUI 中创建具有多个子视图(如 VStack)的视图