11

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 => {}
    _ => {}
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Thomas Braun
  • 505
  • 3
  • 14

1 Answers1

16

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));
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Peter Varo
  • 11,726
  • 7
  • 55
  • 77
  • 1
    Beautiful; thank you! – Thomas Braun May 12 '19 at 15:40
  • 2
    No worries, I'm glad if I could help! – Peter Varo May 12 '19 at 15:41
  • On an extended note for later consideration: The rust team really should add directly matching type-parameters to primitives'/structs without the added loop of implementations. Where art thou, Rust-Lang Team? – Thomas Braun May 12 '19 at 17:00
  • @ThomasBraun well, you could achieve something similar with [proc-macros](https://doc.rust-lang.org/reference/procedural-macros.html), are you familiar with those? Since you are working at the AST level, you could match against the types there. – Peter Varo May 12 '19 at 17:03
  • 1
    Although, the two would have different effects: if your `do_something` is complex and long and it is very different from type to type, and invoked more than once, it is better to have them as functions in the `impl` blocks over inserting the same function bodies over and over again for example. – Peter Varo May 12 '19 at 17:07