英文:
How to concat two variables to create an identifier in a declarative macro?
问题
If you want to concatenate the two variables $name and $test_name to output one string, you can use the concat! macro in Rust. Here's how you can modify the line in your code to achieve this:
Replace this line:
fn $name_\$test_name() {
With this line:
fn concat!($name, "_", $test_name)() {
This change will concatenate the two variables $name and $test_name with an underscore in between to create the function name. For example, if $name is foo and $test_name is bar, it will output foo_bar.
英文:
I want to write a macro to support parameterized tests, and got the following code from AI, but got errors on one line:
#[macro_export]
macro_rules! parameterize {
($name:ident, $params:pat, {$($test_name:ident : ($($args:expr),*)),*}, $test_body:block) => {
$(
fn $name_$test_name() { //<========= this line
let $params = ($($args),*);
$test_body
}
)*
};
}
parameterize! {
should_be_added,
(expected, a, b),
{
positive: (3, 1, 2),
zero: (0, 0, 0),
negative: (-5, -2, -3),
large_numbers: (999999, 444444, 555555)
},
{
println!("a={}, b={}, expected={}", a, b, expected);
}
}
fn main() {
positive();
negative();
}
If I change fn $name_\$test_name() to fn $test_name() , it works well.
So I want to know how to concatenate the two variables $name $test_name to output one string. For example, if $name is foo and $test_name is bar, how to output foo_bar?
答案1
得分: 1
以下是翻译好的部分:
"paste" 是一个crate called paste ,它提供了一个用于在声明性宏中连接标记的宏。
要使用它,将整个结果包装在 paste! 宏中,然后通过将它们放在 [< 和 >] 之间并用空格分隔来连接标记。
use paste::paste;
#[macro_export]
macro_rules! parameterize {
($name:ident, $params:pat, {$($test_name:ident : ($($args:expr),*)),*}, $test_body:block) => {
paste! {
$(
fn [< $name _ $test_name >]() { // <- paste! 使用的特殊语法!
let $params = ($($args),*);
$test_body
}
)*
}
};
}
使用您提供的其余代码,这将生成函数 should_be_added_positive 和 should_be_added_negative。
英文:
There is a crate called paste, that provides a macro for concatenating tokens inside declarative macros.
To use it, wrap your entire result in the paste! macro, and then you can concatenate tokens by placing them between [< and >] with spaces to separate.
use paste::paste;
#[macro_export]
macro_rules! parameterize {
($name:ident, $params:pat, {$($test_name:ident : ($($args:expr),*)),*}, $test_body:block) => {
paste! {
$(
fn [<$name _ $test_name>]() { // <- special syntax used by paste!
let $params = ($($args),*);
$test_body
}
)*
}
};
}
Using the remainder of the code you've provided, this would generate functions should_be_added_positive and should_be_added_negative.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论