在 Rust 宏中将 ident 视为字符串

rei*_*ish 2 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. Rename it to $new and put it under the section [$section]",
        );

        &$config.$old
    } else {
        if let Some(section) = &$config.$section {
            &section.$new
        } else {
            &None
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

}

这似乎没有按预期工作,因为宏参数没有在字符串中替换。如何改变宏才能达到想要的效果?

mca*_*ton 8

stringify!宏可以将一个元素转换为字符串文字,并且该concat!宏可以将多个文字连接成一个字符串文字:

println!(
    concat!(
        stringify!($old),
        " configuration option is deprecated. Rename it to ",
        stringify!($new),
        " and put it under the section [",
        stringify!($section),
        "]",
    )
);
Run Code Online (Sandbox Code Playgroud)

游乐场的永久链接