Mystor
Mystor

Reputation: 365

Capturing lifetimes in rust macro_rules

In macro_rules! you can state the different types of things to parse after the colon (such as $x:ident for identifiers, or $y:ty for types), however I am confused as to how I would declare that I want to capture a lifetime, like 'a or 'static. Is this possible right now?

Upvotes: 6

Views: 4332

Answers (3)

Luro02
Luro02

Reputation: 288

You can capture lifetimes in macros with the lifetime specifier:

macro_rules! match_lifetimes {
    ( $( lt:lifetime ),+ ) => {}
}

match_lifetimes!( 'a, 'b, 'static, 'hello );

playground

You can read more about the lifetime specifier in the RFC or the rust reference.


In case you just want to match the generics of a type you might be better off using tt instead:

struct Example<'a, T>(&'a T);

macro_rules! match_generics {
    ( $typ:ident < $( $gen:tt ),+ > ) => {}
}

match_generics!( Example<'a, T> );

playground

Upvotes: 4

lovasoa
lovasoa

Reputation: 6855

If you want to create a new generic lifetime parameter from an argument given to your macro, then you have to match it with $my_lifetime:tt (see playground) :

macro_rules! my_macro {
    ($a:tt) => { struct MacroDefined<$a> { field: &$a str } }
}

Upvotes: 0

J W
J W

Reputation: 9

You can capture them as $exprs.

Upvotes: 0

Related Questions