Attribute macro
An attribute macro is a compile-time procedural transformation attached to a language item that generates replacement or additional code.
Write Powerful Rust Macros
An attribute macro is a Rust procedural macro that defines a custom attribute and replaces the annotated item with generated output.
- How it is used
- Transforms annotated Rust items when existing definitions need modification rather than additive functionality.
- How deep it goes
- Works through parsing struct fields, matching AST variants, quoting replacement output, and parsing configurable attribute arguments.
- Examples
- Demonstrates a public-fields struct transformation, configurable excluded fields, panic-to-Result function rewriting, and configuration-struct generation.
- What you can do after
- Build it from scratch by parsing annotated items and arguments, then generating replacement Rust tokens with quote!.
Read how Write Powerful Rust Macros explains attribute macro →
Idiomatic Rust
An attribute macro is a procedural macro attached to an existing item that can accept attribute arguments and generate replacement or additional code.
- How it is used
- Distinguishes procedural macro forms by where they attach and whether they accept attribute arguments.
- How deep it goes
- Defines placement and argument support, but stops short of implementing an attribute macro.
- Examples
- Shows the attribute form #[MyAttribute] without a worked implementation.
- What you can do after
- Evaluate its fit by checking whether a macro should attach to an existing item and accept attribute arguments.
Related concepts
- procedural macrokind of · A procedural macro is a Rust macro implemented as a program that transforms an input token stream into generated code during compilation.
- derive macrocontrasts with · A Rust derive macro is an attribute that automatically generates implementations of specified traits or related functionality for a type.
- conditional compilationincludes · Conditional compilation selects source-code regions for inclusion or exclusion based on conditions evaluated during compilation or preprocessing.
- TokenStreamuses · TokenStream is a sequence of Rust source tokens used as input or output during procedural macro expansion and code generation.
- functionuses · A function is a callable program unit that performs an operation, may accept inputs, and can produce a result or side effect.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

