Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I match on the concrete type of a generic parameter? [duplicate]

Tags:

types

match

rust

I have a function with a type parameter U that returns an Option<U>. U is bound by the trait num::Num. As such, U can be a usize, u8, u16, u32, u64, u128, isize, etc.

How do I match U? E.g.,

match U {
    u8 => {},
    u16 => {}
    _ => {}
}
like image 633
Thomas Braun Avatar asked May 12 '19 15:05

Thomas Braun


1 Answers

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));
}
like image 173
Peter Varo Avatar answered Oct 12 '22 23:10

Peter Varo