[英]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.
您可以在冒号后说明要解析的不同类型的事物(例如 $x:ident 表示标识符,或 $y:ty 表示类型),但是我对如何声明我想要捕获一生感到困惑,像 'a 或 'static。 Is this possible right now?
这现在可能吗?
You can capture lifetimes in macros with the lifetime
specifier:您可以使用
lifetime
说明符在宏中捕获生命lifetime
:
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 .您可以在RFC或Rust 参考中阅读有关
lifetime
说明符的更多信息。
In case you just want to match the generics of a type you might be better off using tt
instead:如果您只想匹配类型的泛型,则最好使用
tt
代替:
struct Example<'a, T>(&'a T);
macro_rules! match_generics {
( $typ:ident < $( $gen:tt ),+ > ) => {}
}
match_generics!( Example<'a, T> );
您可以将它们捕获为 $exprs。
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 ) :如果你想从给你的宏的参数创建一个新的通用生命周期参数,那么你必须将它与
$my_lifetime:tt
匹配( 参见 playground ):
macro_rules! my_macro {
($a:tt) => { struct MacroDefined<$a> { field: &$a str } }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.