Why does tt in declarative macros not expect the token "::"?

Viewed 35

I have written the following macro:

macro_rules! foo {
    ($bar:tt) => {
       fn baz() {
           $tt
       }
    }
}

I am using it like this:

foo! {
    String::new();
}

This produces the following error: error: no rules expected the token :: label: no rules expected this token in the macro call

I find this very confusing since I was under the impression that tt can match any regular code token.

1 Answers

tt matches a single token tree, i.e. only the String. If you want to match any sequence of tokens, use repeated tt:

macro_rules! foo {
    ($($bar:tt)*) => {
       fn baz() {
           $($bar)*
       }
    }
}
Related