No rules expected this token in macro call

Could somebody explain why this not works with trailing comma on last field ?

macro_rules! packet {
    (
        $(opcode $opcode_value:expr;)?
        $(#[$outer:meta])*
        $vis:vis struct $PacketStruct:ident {
            $($field_name:ident: $field_type:ty),*
        }
    ) => {
        $(#[$outer])*
        #[derive(Copy, Clone)]
        $vis struct $PacketStruct {
            $($field: $field_type),*
        }
    };
}

fn main() {
    packet! {
        pub struct Outcome {
            name: String,
            os: u8,
            game_name: String,
        }
    }
}

on compile this code returns error:

error: no rules expected the token `}`
  --> src/main.rs:23:9
   |
1  | macro_rules! packet {
   | ------------------- when calling this macro
...
23 |         }
   |         ^ no rules expected this token in macro call

error: could not compile `playground` due to previous error

Sandbox.

If I remove trailing comma after last field in struct all works OK. But it's unclear why

It's because $( ... ),* only matches with the comma between them, not after. You can add an $(,)? at the end of the pattern to allow a trailing comma.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.