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 => {}
_ => {}
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With