macro_rules! if_match {
($(let $expr:pat =)* $cond:expr => $then:expr $(,)*) => { ... };
($(let $expr:pat =)* $cond:expr => $then:expr, else => $elsethen:expr $(,)*) => { ... };
($(let $expr:pat =)* $cond:expr => $then:expr, $($(let $expr2:pat =)* $else_cond:expr => $else_then:expr,)* else => $else_expr:expr $(,)*) => { ... };
($(let $expr:pat =)* $cond:expr => $then:expr, $($(let $expr2:pat =)* $more:expr => $more_then:expr $(,)* )*) => { ... };
() => { ... };
}
Expand description
A macro to make big else if conditions easier to read:
let s = "bateau";
if_match! {
s == "voiture" => println!("It rolls!"),
s == "avion" => println!("It flies!"),
s == "pieds" => println!("It walks!"),
s == "fusée" => println!("It goes through space!"),
s == "bateau" => println!("It moves on water!"),
else => println!("I dont't know how it moves...")
}
You can use it just like you would use conditions:
let x = -1;
let result = if_match! {
x >= 0 => "it's a positive number",
else => "it's a negative number",
};
assert_eq!(result, "it's a negative number");
And of course, the else
condition is completely optional:
let x = 12;
if_match! {
x & 1 == 0 => println!("it is even"),
x & 1 == 1 => println!("it is odd"),
}
Want to use if let
conditions too? Here you go:
let v = 12;
let y = if_match! {
let 0 = 1 => 0,
v < 1 => 1,
v > 10 => 10,
let 0 = 1 => 0,
else => v
};
assert_eq!(y, 10);