gpt4 book ai didi

Rust 对长 Trait 约束链使用宏

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

我的实现中有很多冗长且重复的特征约束链,我想替换它们。特征的类型别名看起来不错但是 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/

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