如何匹配泛型参数的具体类型?

Tho*_*aun 5 types match rust

我有一个带有类型参数的函数,U它返回一个Option<U>. U受 trait 的约束num::Num。这样,U可以是usizeu8u16u32u64u128isize,等。

我如何匹配U?例如,

match U {
    u8 => {},
    u16 => {}
    _ => {}
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*aro 10

我假设您希望与类型匹配的原因是因为您希望在编译时而不是运行时进行切换。不幸的是,Rust 没有那种检查(还没有?),但是您可以做的是为此创建一个特征,然后您可以为您想要使用的类型实现:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 不用担心,如果我能帮上忙,我很高兴! (2认同)

归档时间:

查看次数:

3532 次

最近记录:

6 年,5 月 前