在 Rust 宏中将标识视为字符串

Treating idents as string in 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
        }
    }
};

}

这似乎没有像预期的那样工作,因为宏参数没有在字符串中被替换。如何更改宏以达到预期效果?

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