rust - 在Rust宏中将身份视为字符串

标签 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
        }
    }
};

}

由于宏参数未在字符串内替换,因此这似乎无法按预期工作。如何更改宏以达到所需的效果?

最佳答案

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/

相关文章:

rust - 在声明性宏中构建所有元素对(二次集)

rust - 实现 proc 宏时的循环包依赖

rust - 如何导出同名的函数和宏?

rust - 如何使用宏根据架构定义具有不同调用约定的函数?

rust - 如何使用 wasm-bindgen 调用作为模块的 JavaScript 函数?

mongodb - 使用 Rust 更新 MongoDB 中的数据

generics - 是否可以为除了一个类型子集以外的所有类型都可以使用的特征创建通用的impl?

rust - 如何在 Rust 中通过宏生成 const 数组?

methods - 如何为此Rust特征使用相同的默认实现

Rust 包装包含通用特征的单个特征