Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding matches! macro

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;

  1. $(|)?
  2. $(,)?

I understand the functionality of ?:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading