Best way to make a macro with required and optional arguments?

This is what I've come up with, but are there any other commonly used techniques/best practices?

macro_rules! example {
    ($req1:expr, $req2:expr) => {
        example!($req1, $req2,)
    };
    ($req1:expr, $req2:expr, $($optional:expr),*) => {
        // Macro body
    };
}

You could also do this, I guess

macro_rules! example {
    ($req1:expr, $req2:expr $(,$optional:expr)*) => {
        // Macro body
    };
}

You can use the following syntax to denote an optional parameter:

macro_rules! example {
    ($req:expr, $($optional:expr)?) => {};
}

More specifically:

$(Body)Delim?

Okay, that's helpful, thanks! However, is there a "best practice" way to have any number of optional arguments?

Well, in your first example you used something like this:

macro_rules! example {
    ($req1:expr, $req2:expr, $($optional:expr),*) => {
        // Macro body
    };
}

Which on its own includes the following cases:

example!(a, b, 1, 2, 3);
example!(a, b,);

Because the * repeat includes none:

  • *: 0 or more
  • +: 1 or more
  • ?: 0 or 1

Yeah, I'm hoping for a way to call the macro with only required arguments and no trailing commas, though:
example!(a, b);

Hmm, maybe the following would work?

macro_rules! example {
    ($a:expr, $b:expr $(, $many:expr)*) => {};
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.