我有一个配置结构,其中包含一些顶级属性,我想在其中进行介绍。为了提供弃用警告,我做了以下宏
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
}
}
};
}
由于宏参数未在字符串内替换,因此这似乎无法按预期工作。如何更改宏以达到所需的效果?
最佳答案
stringify!
宏可以将元素转换为字符串文字,而concat!
宏可以将多个文字转换为单个字符串文字:
println!(
concat!(
stringify!($old),
" configuration option is deprecated. Rename it to ",
stringify!($new),
" and put it under the section [",
stringify!($section),
"]",
)
);
Permalink to the playground
关于rust - 在Rust宏中将身份视为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62236784/