A question about repetition in macro declaration


#1

When declaring the repetition in macro, e.g.,

macro_rules! vec {
    ( $( $x:expr ),* ) => {
...

, which is copied from here.

The pattern ($(...), *) seems should match 1,2,3,, rather than 1,2,3 (note the last ,). Why vec![1,2,3] is valid and why the compiler not complain that there missed a ,?


#2

Because the , in ),* is a separator, not a terminator.

If you want to match a terminator, use ,)* so that the comma is inside the repetition.


#3

And if you want to support either use

macro_rules! vec {
    ( $( $x:expr ),* $(,)* ) => {

(soon you may be able to use the more correct $( $x:expr ),* $(,)? to avoid someone writing vec![1, 2, 3,,,,,,,], but that’s not a massive issue).