我正在 Rust 中尝试使用宏,并希望进行嵌套扩展,即组合。
这是我编写的代码:
macro_rules! nested {
(
$(arg $arg:ident;)*
$(fun $fun:ident;)*
) => {
$(
$fun($($arg),*);
)*
}
}
fn show1(a: i32, b: i32, c: i32) {
println!("show1: {} {} {}", a, b, c);
}
fn show2(a: i32, b: i32, c: i32) {
println!("show2: {} {} {}", a, b, c);
}
fn main() {
let a = 1;
let b = 2;
let c = 3;
nested! {
arg a;
arg b;
arg c;
fun show1;
fun show2;
}
}
我希望这能扩展到
fn main() {
let a = 1;
let b = 2;
let c = 3;
// iteration over $fun
show1(/* iteration over $arg */a, b, c);
show2(/* iteration over $arg */a, b, c);
}
然而,似乎Rust不支持此操作,反而会报错:
error: inconsistent lockstep iteration: 'fun' has 2 items, but 'arg' has 3
显然,它忽略了内部迭代。
但是,如果我删除其中一个参数,使其对两个参数都有2项,它仍然会抱怨:
<anon>:7:18: 7:25 error: attempted to repeat an expression containing no
syntax variables matched as repeating at this depth
<anon>:7 $fun($($arg),*);
有没有一种方法可以做到我想要的?