更新时间:2023-12-01 10:53:10
您可以使用tt
(单个令牌)标识符来接受您希望在另一个宏指令组中使用的生存时间(
You could use a tt
(single token) identifier to accept a lifetime you want in another macro arm (playground link)
macro_rules! impl_FooTrait {
($name:ty, $lifetime:tt) => {
impl<$lifetime> $crate::FooTrait for $name { }
};
($name:ty) => {
impl $crate::FooTrait for $name { }
};
}
struct Bar(i32);
impl_FooTrait!(Bar);
struct Baz<'a>(&'a i32);
impl_FooTrait!(Baz<'a>, 'a); // Use and declare the lifetime during macro invocation
这是实际上实现某些内容的示例.
我猜这有点奇怪.我有兴趣查看其他替代答案.可能有更好的方法可以做到这一点.我还不熟悉宏观领域.
Its a bit weird to look at I guess. I am interested to see any alternative answers. There is possibly a nicer way to do this; I'm not well versed in macro land yet.