【问题标题】:Generate attribute value via macro通过宏生成属性值
【发布时间】:2020-04-26 22:52:43
【问题描述】:

假设我有一个名为module_nameident 输入参数。如何通过这个参数生成属性的值?

简单来说,我想生成这样的东西:

macro_rules! import_mod {
    ( $module_name:ident ) => {
        // This does not work,
        // but I want to generate the value of the feature attribute.
        // #[cfg(feature = $module_name)]
        pub mod $module_name;
    }
}

import_mod!(module1);

// #[cfg(feature = "module1")]
// pub mod module1;

【问题讨论】:

标签: rust rust-macros rust-decl-macros


【解决方案1】:

编译器指令中的参数必须是文字。

一种体面的解决方法是采用文字以及您的“功能”:

macro_rules! my_import {
    ( $module_name:ident, $feature_name:literal ) => {
        #[cfg(feature = $feature_name)]
        mod $module_name;
    }
}

my_import!(foo, "foo");

供参考 - https://doc.rust-lang.org/stable/reference/attributes.html#meta-item-attribute-syntax

总结一下:大多数内置属性都有规则#[<attribute> = <literal>]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多