Why can't this macro handle trailing comma?

98 Views Asked by At
#[macro_export]
macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

The book says "The comma following $() indicates that a literal comma separator character could optionally appear after the code that matches the code in $(). The * specifies that the pattern matches zero or more of whatever precedes the *."

I notice that this matches vec![1,2,3,4] but not vec![1,2,3,4,] which should match according to the interpretation above. The comma is certainly not optional in the middle and must not appear optionally at trailing position according to the compiler. But if * governs the whole '$( $x:expr ),' then 1,2,3,4, should exactly matches 4 times.

From the result of the compiler I guess it is not like regular expressions but the $(),* is more like a join rule as ','.join(...)?

0

There are 0 best solutions below