我正在尝试创建一个宏来帮助我一直在重复编写的一些样板枚举代码。我设法使用基本的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
如何在一个subnested环境中工作。
更新1
我在一些特征实现中使用$name
进行模式匹配。例如,我有一些类似于下面的代码:
match raw {
$(
$type::$name => { /* a result of some sort */ },
)+
}