rustrust-macrosrust-decl-macros

How to match a trait in a Rust macro?


My goal is to take as input trait type.

my_test_macro!(Trait1, Trait2<Test1, Test2=Test3>)

What I tried so far was writing parser like this.

$( $ty:ident < $( $N:ident $(: $b0:ident $(+$b:ident)* )? ),*  $($tname:ident=$ttype:ident),* > )+*

But it created local ambiguity.

error: local ambiguity: multiple parsing options: built-in NTs ident ('N') or ident ('tname').

Solution

  • You can use the ty or path metavariables, depending on what you want to do:

    macro_rules! my_test_macro {
        ($t1:ty, $t2:path) => {};
    }
    
    fn main() {
        my_test_macro!(Trait1, Trait2<Test1, Test2 = Test3>);
    }
    

    See also: