Reputation: 11408
I have an
enum EntryPoints {
A(),
B(),
}
Is it possible to create a macro to adds an enum case, like this?
use some_lib::make_callback;
enum EntryPoints {
A(),
B(),
make_callback!(),
}
which expands to smething like
enum EntryPoints {
A(),
B(),
SomeLibCallback(data: u64),
}
All my attempts to create a very simple example lead to syntax errors and I don't find anything on the web.
Upvotes: 1
Views: 294
Reputation: 15012
You can't call macros within the body of an enum declaration, but you can pass the enum declaration into the macro instead:
macro_rules! make_callback {
{ enum $name:ident { $($inner:tt)* } } => {
enum $name {
SomeLibCallback(u64),
$($inner)*
}
}
}
make_callback! { enum EntryPoints {
A(),
B(),
} }
// expansion
enum EntryPoints {
SomeLibCallback(u64),
A(),
B(),
}
{ $($inner:tt)* }
essentially just says to match any arbitrary sequence of tokens within the set of curly braces, and $($inner)*
then expands that sequence back into the new enum body.
Upvotes: 4