I’m trying to understand how the matches! macro is written.
macro_rules! matches {
($expression:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
match $expression {
$( $pattern )|+ $( if $guard )? => true,
_ => false
}
};
}
Two metavariables are not clear to me;
$(|)?$(,)?
I understand the functionality of ?:
indicates an optional fragment with zero or one occurrences.
But I’m not understanding where these metavariables are used for.
>Solution :
They are not used for anything, they are syntactic allowances.
$(|)? makes it so you can start the pattern with a leading |, for uniformity with e.g. match patterns which also allow that:
matches!(a, |1|2);
If you create a copy of the macro and remove that group, you’ll see that that syntax does not work anymore.
This is because while the leading | is part of the Pattern production pat_param matches the PatternNoTopAlt production, and so does not include or allow for a leading |.
Similarly, the trailing $(,)? allows for a trailing comma on the pattern: rust supports trailing commas in function calls, so most expression-like and function-like macros will also support it as they make for convenient uniformity:
matches!(
a,
1|2,
);
Here again, if you create a copy of the macro and remove that group, trailing commas will fail to parse.