【问题标题】:Is it possible to write a macro that counts items and generates an enum?是否可以编写一个计算项目并生成枚举的宏?
【发布时间】:2016-08-20 11:16:35
【问题描述】:

我想要这样的东西:

define_enum_and_all_variants! ( Test {
    One, Two, Three
});

生产:

enum Test {
  One, Two, Three
}
const ALL_VARIANTS: [Test; 3] = [One, Two, Three];

这里的问题是3,我可以这样写:

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中的元素个数?

【问题讨论】:

    标签: macros rust


    【解决方案1】:

    这并不能真正回答问题,而只是因为你有一个xy problem

    而不是写

    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! 宏,而是如何结合count! 宏的模拟和生成enum 的主宏。但这并不重要,因为错过了&[] 解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 2013-05-18
    • 2015-07-21
    • 2011-01-07
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    相关资源
    最近更新 更多