module-concept

Rust Conditional attributes

Apply an attribute only when the predicate holds. Unlike cfg itself, cfg_attr does not remove the item unless the resulting attribute does so. It can help apply target-specific documentation or lint settings. Expected result (not executed): 9 Why: all() with no arguments is true, so a documentation attribute is applied. Common mistake: Assuming cfg_attr always removes the annotated function.

Formal Syntax & Structure

rust syntaxrust
#[cfg_attr(predicate, attribute)]

Working Example

Example Snippetrust
#[cfg_attr(all(), doc = "Always available in this example.")]fn score() -> u32 { 9 }fn main() { println!("{}", score()); }
Rust Reference