Rust 对长 Trait 约束链使用宏

标签 rust macros traits

我的实现中有很多冗长且重复的特征约束链,我想替换它们。特征的类型别名看起来不错但是 it is still an unstable feature .

我试过用这样的东西

trait NumericTrait : Float + FromPrimitive + ToPrimitive + RealField + Copy + Clone + Debug + 'static {}

然而,这会导致问题,因为 NumericTrait 并未针对我所关注的类型明确实现。相反,所有基本特征都是。

我现在认为宏是可行的方法,所以我尝试了以下方法:

macro_rules! numeric_float_trait {
    () => {
        Float + FromPrimitive + ToPrimitive + RealField + Copy + Clone + Debug + 'static
    };
}

struct SomeStruct;

impl<T> SomeStruct 
where
    T: numeric_float_trait!()
{
    fn do_things(num: T) {
        println!("I got this num {:?}", num);
    }
}

但是语法不正确,编译器不会接受它。我如何实现通过宏基本上粘贴特征列表的所需功能?

最佳答案

您可以声明创建您想要的特征的宏,如下所示:

macro_rules! declare_trait {
    ($trait_type:ident,$trait_name:ident) => {
        trait $trait_name:
            $trait_type
            + num::FromPrimitive
            + num::ToPrimitive
            + alga::general::RealField
            + ::std::marker::Copy
            + ::std::clone::Clone
            + ::std::fmt::Debug
            + 'static
        {
        }

}

在您的宏中,您需要定义具有以下给定特征的任何 T 的实现:

impl<T> $trait_name for T where
    T: $trait_type
      + num::FromPrimitive
      + num::ToPrimitive
      + alga::general::RealField
      + ::std::marker::Copy
      + ::std::clone::Clone
      + ::std::fmt::Debug
      + 'static
{
}

现在你只需要调用这个宏来声明你想要的特征:

declare_trait!(Float, NumericFloatTrait); // Float is type and NumericFloatTrait is the name here

声明特性后,您可以在任何地方使用它:

struct SomeStruct;

impl SomeStruct {
    fn do_things_with_float<T: NumericFloatTrait>(num: T) {
        println!("I got this float {:?}", num);
    }
}

Playground

关于Rust 对长 Trait 约束链使用宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848209/

相关文章:

rust - 使用生命周期参数为特征分离可变借位

rust - 如何同时运行包含借来的TcpStream的 future ?

rust - 如何从单击按钮的条目中获取信息?

c - C 标准是否有任何限制允许将函数实现为宏?

c - 如何在 eclipse 中重命名(重构)c 宏

rust - VecDeque和Vec是否都具有特征?

regex - Rust 正则表达式模式 - 无法识别的转义模式

rust - 线程 'main' 在 'index out of bounds: the len is 2 but the index is 2' 崩溃时 panic

c - 产生错误数字的宏

scala - 如何解决 "Implementation restriction: trait ... accesses protected method ... inside a concrete trait method."