在macro_rules中使用可选数据表示枚举变体

时间:2015-11-11 17:13:22

标签: enums rust

我正在尝试创建一个宏来帮助我一直在重复编写的一些样板枚举代码。我设法使用基本的macro_rule相对容易地实现了一个简单的枚举(即没有参数)。例如摘录:

macro_rules! enum_helper {
    ($type:ident, { $( $name:ident ), * }) => {
        enum $type {
            $(
                $name,
            )+
        }

        impl FromSql for $type {
            fn from_sql<R: Read>(_: &Type, raw: &mut R, _: &SessionInfo) -> Result<&type> {
                // ... the implementation
        }

        // ... plus some other internal traits being implemented
    }
}

enum_helper!(Step, {
    Step1,
    Step2
});

我希望扩展这个宏以支持一组混合的枚举样式,主要只有一个类型参数,例如。

enum_helper!(Step, {
    Step1,
    Step2,
    Step3(i64)
});

有没有办法用macro_rules表示这个“可选”参数?我怀疑它涉及使用tt但是我仍然有点迷失tt如何在一个subnested环境中工作。

更新1

我在一些特征实现中使用$name进行模式匹配。例如,我有一些类似于下面的代码:

match raw {
    $(
        $type::$name => { /* a result of some sort */ },
    )+
}

0 个答案:

没有答案
相关问题