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;
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>]