gpt4 book ai didi

rust - 如何提供可选泛型作为 macro_rules 参数?

转载 作者:行者123 更新时间:2023-11-29 08:28:16 26 4
gpt4 key购买 nike

我想使用 macro_rules 来创建一个特征的实现。类型应作为宏参数给出。但是,其中一些类型可能包含生命周期,所以我需要它们。我还有一个来自宏内部的泛型类型。结果应该是这样的

impl<T> Foo<T> for MyType { .. }
// Or with lifetime:
impl<'a, 'b, T> Foo<T> for LifetimeType<'a, 'b> { .. }

如何构造宏以及如何调用它?

最佳答案

您可以使用 lifetime 说明符来匹配宏参数中的生命周期:

trait Foo{}

macro_rules!impl_foo {
($($l:lifetime),*; $t:tt) => { impl<$($l),*> Foo for $t<$($l),*> {} };
($t:ty) => { impl Foo for $t {} };
}

然后这样调用它:

impl_foo!(A);
impl_foo!('a, 'b; B);

Playground

请注意,我能找到的唯一提到捕获的 lifetime 说明符的地方是 the associated RFC .它在 The little book of Rust macros 中特别明显缺失, 尽管它在 2016 年合并了……

关于rust - 如何提供可选泛型作为 macro_rules 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400467/

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