TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
cfg (configuration) attribute is a built-in Rust attribute used for conditional compilation. It instructs the Rust compiler (rustc) to include or exclude the annotated Abstract Syntax Tree (AST) node based on compile-time configuration predicates. If the predicate evaluates to false, the compiler completely strips the item from the AST. This evaluation and stripping occur during the macro expansion phase, meaning macros can generate code containing cfg attributes, which the compiler will then evaluate in that same pass.
Syntax and Placement
The attribute can be applied as an outer attribute to specific items (functions, structs, modules, statements, etc.) or as an inner attribute to apply to the entire enclosing module or crate.Configuration Predicates
Thecfg attribute evaluates predicates that fall into three primary categories:
- Cargo Features: The most idiomatic way developers interact with
cfgis through Cargo features. Cargo automatically translates features defined inCargo.tomlinto name-value pair flags (--cfg feature="name") passed torustc.
- Boolean Flags: Evaluates to true if the configuration flag is currently set in the compilation environment.
any(...): Evaluates to true if at least one comma-separated predicate within the parentheses evaluates to true.
The cfg_attr Attribute
The cfg_attr attribute is a closely related built-in attribute used to conditionally apply other attributes to an item. It takes a configuration predicate followed by a comma-separated list of attributes to apply if the predicate evaluates to true.
Custom Configurations
Beyond Cargo features and built-in compiler targets, custom configuration flags can be passed directly torustc using the --cfg command-line flag or emitted via a build.rs script using the cargo::rustc-cfg instruction.
The cfg! Macro
While the #[cfg] attribute removes code from the AST, Rust also provides the cfg!() macro for inline boolean evaluation. The macro takes the exact same predicates as the attribute but evaluates to a boolean literal (true or false) at compile time.
#[cfg] attribute, code inside a branch controlled by cfg!() must still be syntactically valid and pass the borrow checker and type checker on all platforms, because the AST nodes are not stripped.
Master Rust with Deep Grasping Methodology!Learn More





