英文:
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"
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论