这是我想要的合成例子:
macro_rules! define_enum {
($Name:ident { $($Variant:ident),* }) => {
pub enum $Name {
None,
$($Variant),*,
}
}
}
define_enum!(Foo { A, B });
Run Code Online (Sandbox Code Playgroud)
此代码编译,但如果添加逗号:
define_enum!(Foo { A, B, });
// ^
Run Code Online (Sandbox Code Playgroud)
编译失败.我可以解决它:
($Name:ident { $($Variant:ident,)* })
// ^
Run Code Online (Sandbox Code Playgroud)
但后来define_enum!(Foo { A, B });失败了,
我应该如何编写一个宏来处理这两种情况:
define_enum!(Foo { A, B });
define_enum!(Foo { A, B, });
Run Code Online (Sandbox Code Playgroud) 我目前正在研究Rust宏,我找不到任何有关重复的详细文档.我想用可选参数创建宏.这是我的想法:
macro_rules! single_opt {
($mand_1, $mand_2, $($opt:expr)* ) =>{
match $opt {
Some(x) => println!("1. {} 2. {}, 3. {}", $mand_1, $mand_2, x);
None => single_opt!($mand_1, $mand_2, "Default");
}
}
}
fn main() {
single_opt!(4,4);
}
Run Code Online (Sandbox Code Playgroud)
这个例子似乎已经过时了,因为我无法编译它.Rust书中非常简短地提到了这个主题.我如何让这个例子起作用?