问题
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