attribute
#[cfg_attr] — Apply attributes conditionally
Conditionally attach one or more attributes. When the predicate is false, the listed attributes are not added; the item itself is not automatically removed. Useful for optional derives or documentation attributes. Result: Conditional attribute application. Compiler flags: --cfg bytemind_debug. Expected output (not executed): 'Ticket(7)\nID: 7\n' Common mistake: Assuming cfg_attr by itself removes the annotated struct.
Formal Syntax & Structure
rust syntaxrust
#[cfg_attr(predicate, attribute, ...)]Working Example
Example Snippetrust
#[cfg_attr(bytemind_debug, derive(Debug))]struct Ticket(u32);fn main() { let ticket = Ticket(7); #[cfg(bytemind_debug)] println!("{ticket:?}"); println!("ID: {}", ticket.0);}