Macro matrix_match::matrix_match
source · macro_rules! matrix_match { ( ($first:expr, $sec:expr) ; $($patS:pat),+ => $( $patF:pat => $($ex:expr),+);+ $(;)? ) => { ... }; }
Expand description
Macro to match on a pair of values.
Usage
matrix_match!(
(a, b) ; B::a , B::b =>
A::a => "aa" , "ab" ;
A::b => "ba" , "bb" )
First matches the first value to the patterns on the left. Then the second value gets matched to the patterns at the top. The expression at the intersection of both matches is what is eventually ran and possibly returned.
Destructuring is also possible inside a matrix_match
:
matrix_match!(
(a, b) ; Ok(v) , Err(e) =>
Some(s) => s , s ;
None => v , e )
The same name can be used in separate columns or separate rows. A variable in a column will shadow any variable in a row with the same name!
Full Example
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Light {
Red,
Orange,
Green,
}
fn next(light: Light, car_waiting: bool) -> Light {
use Light::*;
matrix_match!(
(light, car_waiting) ; true , false =>
Red => Green , Red ;
Orange => Red , Red ;
Green => Green , Orange ;
)
}
assert_eq!(next(Light::Red, true ), Light::Green);
assert_eq!(next(Light::Red, false), Light::Red);
assert_eq!(next(Light::Orange, true ), Light::Red);
assert_eq!(next(Light::Orange, false), Light::Red);
assert_eq!(next(Light::Green, true ), Light::Green);
assert_eq!(next(Light::Green, false), Light::Orange);