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