Macros 是否可以编写一个宏来计算项目数并生成枚举?
我想要这样的东西:Macros 是否可以编写一个宏来计算项目数并生成枚举?,macros,rust,Macros,Rust,我想要这样的东西: define_enum_and_all_variants! ( Test { One, Two, Three }); macro_rules! define_enum_and_all_variants { ($Name:ident { $($Variant:ident),* }) => { #[derive(Debug)] enum $Name { $($Variant),*,
define_enum_and_all_variants! ( Test {
One, Two, Three
});
macro_rules! define_enum_and_all_variants {
($Name:ident { $($Variant:ident),* }) =>
{
#[derive(Debug)]
enum $Name {
$($Variant),*,
}
#[allow(dead_code)]
const ALL_VARIANTS: [$Name; 3] = [$($Name::$Variant),*];
}
}
制作:
enum Test {
One, Two, Three
}
const ALL_VARIANTS: [Test; 3] = [One, Two, Three];
这里的问题是3
,我可以这样写:
define_enum_and_all_variants! ( Test {
One, Two, Three
});
macro_rules! define_enum_and_all_variants {
($Name:ident { $($Variant:ident),* }) =>
{
#[derive(Debug)]
enum $Name {
$($Variant),*,
}
#[allow(dead_code)]
const ALL_VARIANTS: [$Name; 3] = [$($Name::$Variant),*];
}
}
但是如何计算
enum
中的元素数?这并不能真正回答问题,只是因为您有一个
而不是写作
const ALL: [u32; 3] = [1, 2, 3];
你可以写
const ALL: &'static [u32] = &[1, 2, 3];
因此,您的宏应该是
const ALL_VARIANTS: &'static [$Name] = &[$($Name::$Variant),*];
回答另一个问题(“如何使用宏计数”):这是一种简单的头尾算法:
macro_rules! count {
($head:ident $(, $tail:ident)*) => { 1 + count!($($tail),*) };
() => { 0 };
}
println!("{}", count!()); // 0
println!("{}", count!(A)); // 1
println!("{}", count!(A, B, C, D)); // 4
谢谢我的问题不是写
count代码>宏,但如何组合您的计数模拟代码>宏和生成枚举的主宏
。但这并不重要,因为缺少&[]
解决方案。