gpt4 book ai didi

macros - 在 rust macro_rules 中捕获生命周期

转载 作者:行者123 更新时间:2023-11-29 08:01:23 34 4
gpt4 key购买 nike

在 macro_rules 中!您可以在冒号后声明要解析的不同类型的东西(例如标识符的 $x:ident 或类型的 $y:ty ),但是我对如何声明我想捕获一生感到困惑,像 'a 或 '静态的。现在这可能吗?

最佳答案

您可以使用 lifetime 说明符在宏中捕获生命周期:

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

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

playground

您可以在 RFC 中阅读有关 lifetime 说明符的更多信息或 rust reference .


如果你只想匹配一个类型的泛型,你最好使用 tt相反:

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

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

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

playground

关于macros - 在 rust macro_rules 中捕获生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594733/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com