使用 Macro_rules 中的可选数据表示枚举变体

2024-02-04

我正在尝试创建一个宏来帮助处理我一直在重复编写的一些样板枚举代码。我设法使用基本的方法相对轻松地实现了一个简单的枚举(即没有参数)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在子嵌套环境中工作。

Update 1

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

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

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Macro_rules 中的可选数据表示枚举变体 的相关文章

随机推荐