0

I have some Rust code equivalent to the snippet below, which doesn't compile

trait A {}
trait B {}

macro_rules! implement {
    ( $type:ty ) => {
        struct C<T: $type> { // <-- Changing "$type" to "A + B" compiles
            t: T,
        }
    }   
}

implement!(A + B); 

fn main() {}

Compiling it with rustc 1.44.1 yields:

error: expected one of `!`, `(`, `,`, `=`, `>`, `?`, `for`, lifetime, or path, found `A + B`

while replacing $type with A + B compiles.

My question is why does this not compile as is, and how can it be changed to do so?

(Note: a bit new to Rust, I am sure there's simpler ways to go about this problem, any advice would be beneficial)

1 Answers1

2

ty macro argument type serves a different purpose: it's a type, not a bound. You may use multiple tokens for that:

macro_rules! implement {
    ( $($token:tt)* ) => {
        struct C<T: $($token)*> {
            t: T,
        }
    }
}
Kitsu
  • 3,166
  • 14
  • 28