gpt4 book ai didi

rust - Rust 宏中的嵌套迭代

转载 作者:行者123 更新时间:2023-11-29 07:44:41 25 4
gpt4 key购买 nike

我正在使用 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;
}
}

Playground

我希望它扩展到

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),*);

有没有办法做我想做的事?

最佳答案

这种扩展好像不行。这是一个解决方法:

macro_rules! nested {
($(arg $arg:ident;)* $(fun $fun:ident;)*) => {
// expand arg to a tuple that will be matched as tt
// in @call_tuple an will be decomposed back to
// a list of args in @call
nested!(@call_tuple $($fun),* @ ($($arg),*))
};
(@call_tuple $($fun:ident),* @ $tuple:tt) => {
$(nested!(@call $fun $tuple))*
};
(@call $fun:ident ($($arg:expr),*)) => {
$fun($($arg),*);
};
}

@id 仅用于保留规则 internal到宏。

关于rust - Rust 宏中的嵌套迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com