Representing enum variants with optional data in macro_rules

左心房为你撑大大i 提交于 2021-02-10 00:36:23

问题


I'm trying to create a macro to help with some boilerplate enum code that I've been repetitively writing. I managed to implement a simple enum (i.e. no arguments) relatively easily using a basic macro_rule. e.g. An excerpt:

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
});

I was hoping to extend this macro to also support a mixed set of enum styles, primarily with only one typed argument e.g.

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

Is there a way to represent this "optional" argument using macro_rules? I suspect it involves using a tt however I'm still a bit lost with how tt works in a subnested environment.

Update 1

I'm using $name within some of the trait implementations for pattern matching. For example, I have some code similar to below:

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

来源:https://stackoverflow.com/questions/33655998/representing-enum-variants-with-optional-data-in-macro-rules

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!