Rust 宏:根据参数数量重复 n 次,而不使用实际参数

nve*_*veo 7 macros repeat rust

是否可以根据参数数量重复某件事 n 次而不使用实际参数?我的用例是实现一个Enum变体,它需要 1 个或多个类型参数以及使用通配符匹配枚举变体的实现。因此通配符的数量将取决于提供的参数的数量。例子:

macro_rules! impl_enum {
    ($name: ident, $($params: ty)+, $val:expr) => {
        enum MyEnum {
            $name($($params)+,)
        }
        impl MyEnum {
            fn get_val(self) {
                match self {
                    MyEnum::$name(??????) => $val
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想要的输出

impl_enum!(Variant1, Type1 Type2 Type3, 42);
Run Code Online (Sandbox Code Playgroud)

成为

            enum MyEnum {
                Variant1(Type1, Type2, Type3),
            }
            impl MyEnum {
                fn get_val(self) {
                    match self {
                        MyEnum::Variant1(_,_,_) => 42,
                    }
                }
            }
Run Code Online (Sandbox Code Playgroud)

这可能吗?

cdh*_*wie 5

您可以使用将 a 转换ty为下划线的宏来完成此操作:

macro_rules! type_as_underscore {
    ( $t: ty ) => { _ };
}
Run Code Online (Sandbox Code Playgroud)

现在,使用它并修复宏中的一些其他错误:

macro_rules! impl_enum {
    ($name: ident, $($params: ty)+, $val:expr) => {
        enum MyEnum {
            $name($($params),+)
        }
        impl MyEnum {
            fn get_val(self) {
                match self {
                    MyEnum::$name($(type_as_underscore!($params)),+) => $val
                };
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)