Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing lifetimes in rust macro_rules

Tags:

macros

rust

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?

like image 844
Mystor Avatar asked Nov 01 '22 15:11

Mystor


1 Answers

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

like image 63
Luro02 Avatar answered Nov 13 '22 01:11

Luro02