首页 > 解决方案 > 如何匹配泛型参数的具体类型?

问题描述

我有一个带有类型参数的函数,U它返回一个Option<U>. U受 trait 约束num::Num。因此,U可以是usize, u8, u16, u32, u64, u128,isize等。

我该如何搭配U?例如,

match U {
    u8 => {},
    u16 => {}
    _ => {}
}

标签: typesrustmatch

解决方案


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));
}

推荐阅读