1
votes

Suppose I have an ident input parameter named module_name. How can I generate the value of the attribute through this parameter?

In simple terms, I want to generate something like this:

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;
1
@Jmb did you manage to apply that answer to OP's? It doesn't work for me. I think this needs proc macros. - Peter Hall
@PeterHall no, you're right, the duplicate answer doesn't work here… - Jmb

1 Answers

1
votes

The argument in the compiler directive must be a literal.

One half decent work-around is to take a literal as well as your 'feature':

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

my_import!(foo, "foo");

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

To summarize: most built in attributes have the rule #[<attribute> = <literal>]