gpt4 book ai didi

rust - 如何在宏中的多个参数上编写嵌套循环?

转载 作者:行者123 更新时间:2023-12-05 03:16:40 25 4
gpt4 key购买 nike

下面的代码

macro_rules! test {
( $( $x1:expr ),*; blub $( $x2:expr ),* ) => {
$(
println!("{} * {} = {}", $x1, $x2, $x1 * $x2);
)*
}
}

fn main() {
test!{1, 2, 3; blub 4, 5, 6};
}

打印:

1 * 4 = 4
2 * 5 = 10
3 * 6 = 18

但是我想像嵌套循环一样分别遍历两个列表。它应该打印:

1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18

我该怎么做?

最佳答案

我发现的唯一方法是通过使用 token 树作为参数之一来作弊:

macro_rules! test {
// secondary invocation with a `[]` delimited list of parameters
// as the first arguments and a single second argument.
( [ $( $x1:expr),* ] ; $x2:expr ) => {
$(
println!("{:?} * {:?} = {:?}", $x1, $x2, $x1 * $x2);
)*
};

// the main invocation of the macro, takes a token tree `x1`
// and a `[]` delimited `,` separated list of arguments for
// each of which it calls itself again with `x1` as first
// parameter and the element of the list as the second
( $x1:tt [ $( $x2:expr ),* ] ) => {
$(
test!($x1; $x2);
)*
};
}

fn main() {
test!{
[1, 2, 3]
[4, 5, 6]
};
}

关于rust - 如何在宏中的多个参数上编写嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74574269/

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