宏以每次从列表中选择的不同值重复相同的代码?

huangapple go评论48阅读模式
英文:

Macro to repeat the same code with 1 value changed each time, picked from a list?

问题

我有点新手对于 Rust 中的宏...如果这已经被问过了,我很抱歉,但我在网上找不到类似的东西,我也不确定这种类型的宏该如何称呼。

我正在寻找一种方法,可以将以下代码减少为:

println!("A");
println!("B");
println!("C");
println!("D");
println!("E");

转换成:

some_macro!(|value| {
  println!(value);
}, ["A", "B", "C", "D", "E"]);

在宏中是否可以包含 Rust 代码?必须是闭包吗,还是...?

英文:

I'm kinda new to macros in Rust... Sorry if this is already asked, but I can't find anything like this online and I'm not sure what this type of macro is even called.

Looking for something that can reduce

println!("A");
println!("B");
println!("C");
println!("D");
println!("E");

into

some_macro!(|value| {
  println!(value);
}, ["A", "B", "C", "D", "E"]);

Is it even possible to have Rust code inside a macro? Does it have to be a closure, or...?

答案1

得分: 2

macro_rules! some_macro {
    ($logic:expr, $($arg:expr),+) => {
        {
            let logic = {$logic};
            $(logic($arg);)+
        }
    };
}

some_macro!(
    |x| println!("{x}"),
    "A",
    "B",
    "C"
);
英文:

Something like this?

macro_rules! some_macro {
    ($logic:expr, $($arg:expr),+) => {
        {
            let logic = {$logic};
            $(logic($arg);)+
        }
    };
}

some_macro!(
    |x| println!("{x}"),
    "A",
    "B",
    "C"

);

huangapple
  • 本文由 发表于 2023年2月9日 02:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定