macro_rules! switch {
($val:expr; $source:ty => { $($name:ident: $type:ty => $expr:expr),+ $(,)? }) => { ... };
}Expand description
Try to match a value with any number of types. This macro does not require
the switch feature.
fn specialized_function<T: Debug + 'static>(val: T) -> String {
cismute::switch!(val; T => {
x: i32 => format!("got an i32: {x}"),
x: char => format!("got a char: {x}"),
}).unwrap_or_else(|x| format!("got something else: {x:?}"))
}
assert_eq!(specialized_function(42_i32), "got an i32: 42");
assert_eq!(specialized_function('!'), "got a char: !");
assert_eq!(specialized_function([1, 2]), "got something else: [1, 2]");It can also be used with (possibly mutable) references:
fn specialized_function<T: Debug + 'static>(val: &mut T) -> String {
cismute::switch!(val; T => {
x: i32 => format!("got an i32: {x}"),
x: char => format!("got a char: {x}"),
}).unwrap_or_else(|x| format!("got something else: {x:?}"))
}
assert_eq!(specialized_function(&mut 42_i32), "got an i32: 42");
assert_eq!(specialized_function(&mut '!'), "got a char: !");
assert_eq!(specialized_function(&mut [1, 2]), "got something else: [1, 2]");