Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add $(,)* or $(,)? to the cheat sheet #35

Closed
Luro02 opened this issue Aug 3, 2019 · 2 comments
Closed

add $(,)* or $(,)? to the cheat sheet #35

Luro02 opened this issue Aug 3, 2019 · 2 comments

Comments

@Luro02
Copy link

Luro02 commented Aug 3, 2019

Some people prefer to have trailing commas, but macros don't allow this by default

macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

vec![ 1, 2, 3, ];

will give a compiler error.

You can fix this by adding $(,)* to the end of the capture like this:

macro_rules! vec {
    ( $( $x:expr ),*  $(,)*) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}

vec![ 1, 2, 3, ];

I got this from https://stackoverflow.com/a/43143459

@ralfbiedert
Copy link
Owner

I'm not sure about this one. Although I agree it's interesting, I have the feeling this is a bit too "special". Is that capture widely used, or a surprising for of syntax over $(x),* that it should be mentioned separately?

@Luro02
Copy link
Author

Luro02 commented Aug 4, 2019

nevermind

@Luro02 Luro02 closed this as completed Aug 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants