在Rust宏中将标识视为字符串
我有一个配置结构,其中包含一些顶级属性,我想将这些属性放在各个部分中。为了提供弃用警告,我制作了以下宏在Rust宏中将标识视为字符串,rust,rust-macros,Rust,Rust Macros,我有一个配置结构,其中包含一些顶级属性,我想将这些属性放在各个部分中。为了提供弃用警告,我制作了以下宏 macro_rules! deprecated { ($config:expr, $old:ident, $section:ident, $new:ident) => { if $config.$old.is_some() { println!( "$old configuration option is deprecated. Renam
macro_rules! deprecated {
($config:expr, $old:ident, $section:ident, $new:ident) => {
if $config.$old.is_some() {
println!(
"$old configuration option is deprecated. Rename it to $new and put it under the section [$section]",
);
&$config.$old
} else {
if let Some(section) = &$config.$section {
§ion.$new
} else {
&None
}
}
};
}
这似乎不像预期的那样有效,因为宏参数在字符串中没有被替换。如何更改宏以达到所需的效果?字符串化代码>宏可以将一个元素转换为字符串文字,而
concat“代码>宏”可以将多个文字连接成单个字符串文字:
println!(
concat!(
stringify!($old),
" configuration option is deprecated. Rename it to ",
stringify!($new),
" and put it under the section [",
stringify!($section),
"]",
)
);
将字符串化代码>宏可以将一个元素转换为字符串文字,而concat“代码>宏”可以将多个文字连接成单个字符串文字:
println!(
concat!(
stringify!($old),
" configuration option is deprecated. Rename it to ",
stringify!($new),
" and put it under the section [",
stringify!($section),
"]",
)
);
不应该是println!(“{}配置选项已弃用。将其重命名为{},并将其放在节[{}]”,$old,$new,$section下)代码>@AlexLarionov那也不行。我不想在$config.$old
中打印struct节的值,我只是想将$old
作为文本打印。它不应该是println吗!(“{}配置选项已弃用。将其重命名为{},并将其放在节[{}]”,$old,$new,$section下)代码>@AlexLarionov那也不行。我不想在$config.$old
中打印struct节的值,我只是想将$old
作为文本打印。