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

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(单令牌)标识符在另一个宏臂(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

这是an example that actually implements something美元.

我想这看起来有点奇怪.我有兴趣看到其他的答案.也许有更好的方法可以做到这一点;我还不太熟悉宏观经济.

Rust相关问答推荐

为什么幻影数据不能自动推断?

如何导入crate-type=[";cdylib;]库?

除了调用`waker.wake()`之外,我如何才能确保future 将再次被轮询?

如何防止Cargo 单据和Cargo 出口发布( crate )项目

如果变量本身不是None,如何返回;如果没有,则返回None&Quot;?

如何将实现多个特征的 struct 传递给接受这些特征为&;mut?

链表堆栈溢出

如何设置activx websocket actorless的消息大小限制?

如何获取光标下的像素 colored颜色 ?

std mpsc 发送者通道在闭包中使用时关闭

.to_owned()、.clone() 和取消引用 (*) 之间有区别吗?

Button.set_hexpand(false) 不会阻止按钮展开

Rust 中的 Option as_ref 和 as_deref 有什么不同

在 Rust 中,为什么整数溢出有时会导致编译错误或运行时错误?

没有通用参数的通用返回

将数据序列化为 struct 模型,其中两个字段的数据是根据 struct 中的其他字段计算的

类型组的通用枚举

如何重写这个通用参数?

如何迭代调用可能会失败的函数?操作员?

list 中没有指定目标 - 必须存在 src/lib.rs、src/main.rs、[lib] 部分或 [[bin]] 部分