具有通用参数的Rust宏接受类型 [英] Rust macro accepting type with generic parameters

查看:129
本文介绍了具有通用参数的Rust宏接受类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现特征impl_Trait!()的宏.现在,它适用于没有泛型参数的类型,但是我不确定如何将类型参数添加到impl关键字.

I have a macro that implements a trait, impl_Trait!(). Right now, it works for types without generic parameters, but I'm not sure how to add the type parameters to the impl keyword.

macro_rules! impl_FooTrait {
    ($name:ty) => {
        impl $crate::FooTrait for $name { ... }
    };
}

struct Bar(i32);
impl_FooTrait!(Bar);
// All OK

struct Baz<'a>(&'a i32);
impl_FooTrait!(Baz<'a>);
// use of undeclared lifetime name `'a`

推荐答案

您可以使用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.

这篇关于具有通用参数的Rust宏接受类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆