Reputation: 365
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
Reputation: 288
You can capture lifetimes in macros with the lifetime
specifier:
macro_rules! match_lifetimes {
( $( lt:lifetime ),+ ) => {}
}
match_lifetimes!( 'a, 'b, 'static, 'hello );
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> );
Upvotes: 4
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