Lifetimes inside macro_rules!

I've been trying to write a macro to help me generate type synonyms (through traits) for closures.

macro_rules! closure_constraint {
    (
        $name:ident,
        for< $lt:ty > FnOnce($arg:ty)
    ) => {
        pub trait $name: for<$lt> FnOnce($arg) {}
    };
}

closure_constraint!(Submit, for<'a> FnOnce(&'a str));

Sadly, this doesn't compile: Rust Playground

However, if you write this manually, or run cargo expand and extract the code from there, then everything works.

Is there a way I can write this differently, so this compiles?

Lifetimes aren't types. This works for your playground.

-        for< $lt:ty > FnOnce($arg:ty)
+        for< $lt:lifetime > FnOnce($arg:ty)
1 Like

Thank you! I wish the error on Rust side would have been better though.

Same.

For historical context, dyn Trait (and dyn Trait + 'lifetime) used to be spelled without the dyn, so when the ... parser or whatever ... expected a type and saw a lifetime, it went look for a + MoreStuff to complete a "trait object" (dyn) type.

But the error should still be improved.

1 Like