How to create a string from macro arguments separated by commas?

I have a macro_rules!, let's call it m!(). I want the following code to print a,b,c,d,e:

fn main() {
    println!("{}", m!(a, b, c, d, e));
}

So I tried:

macro_rules! m {
    { $($i:ident),+ } => { stringify!($($i),+) };
}

But then there are spaces after the commas: a, b, c, d, e.

Then I tried:

macro_rules! m {
    { $($i:ident),+ } => { concat!($(stringify!($i))",",+) };
}

Which didn't compile because there can be only one token as a separator. But even the following does not compile, for a reason I don't understand:

macro_rules! m {
    { $($i:ident),+ } => { concat!($(stringify!($i))","+) };
}

Seems like you cannot have string as a separator at all.

Then I tried:

macro_rules! m {
    { $($i:ident),+ } => { concat!($(stringify!($i), ","),+) };
}

But then there is a comma after the last item: a,b,c,d,e,.

Any ideas?

1 Like

I guess that’s almost it then ^^

Here you go:

macro_rules! m {
    ( $i0:ident $(, $i:ident)* ) => {
        concat!( stringify!($i0) $(, ",", stringify!($i))* )
    }
}
3 Likes

Wow, so many thanks! I've thought about separating the first, but stupidly enough, didn't know how to perform that :smile:

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.