Macro: accept comma after last element

Hi, I am tried to change the Macro example from The Book, to accept comma after last element, but compile failed, any suggestion? Thanks!

#[macro_export]
macro_rules! myvec {
    ( $( $x:expr ),*,? ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}
fn main() {
    let v1 = myvec![1, 2, 3,];
    let v2 = myvec![1, 2, 3];
    println!("{:?}, {:?}",v1, v2 );
}
error: unexpected end of macro invocation
  --> src\main.rs:14:29
   |
2  | macro_rules! myvec {
   | ------------------ when calling this macro
...
14 |     let v1 = myvec![1, 2, 3,];
   |                             ^ missing tokens in macro arguments

Current macro requires input like this.

let v1 = myvec![1, 2, 3,?];

To specify omittable token use this.

( $( $x:expr ),* $(,)? ) => {
1 Like

Thank you!

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.