Invocation Syntax
Derive macros are invoked using the#[derive(...)] attribute placed directly above a data structure declaration.
Architectural Mechanics
When the Rust compiler encounters a#[derive(...)] attribute, it executes the corresponding procedural macro function. The compilation pipeline follows these steps:
- Tokenization: The compiler converts the annotated data structure into a
proc_macro::TokenStream. - Parsing: The macro parses the
TokenStreaminto an AST (usually leveraging thesyncrate’sDeriveInputtype). - Transformation: The macro inspects the AST (e.g., extracting the struct’s identifier, generics, and fields) and constructs new Rust code (usually leveraging the
quotecrate). - Expansion: The macro returns a new
TokenStreamcontaining the generated code. The compiler appends this generatedTokenStreamto the module’s AST in memory during the compilation process; it does not modify or append to the physical source file on disk.
Implementation Structure
Derive macros must be defined in a dedicated crate with theproc-macro = true directive in its Cargo.toml. The macro itself is a public function annotated with #[proc_macro_derive(Name)].
Helper Attributes
Derive macros can declare inert helper attributes. These attributes are scoped exclusively to the item being derived and are used to pass field-level or variant-level metadata to the macro during the parsing phase. Helper attributes are declared in the macro definition using theattributes(...) argument:
Technical Constraints
- Target Restriction: Derive macros can only be applied to
struct,enum, anduniondeclarations. They cannot be applied to functions, modules, or trait definitions. - Additive Only: The output
TokenStreamis appended to the module’s AST. A derive macro cannot mutate, remove, or replace the original data structure definition. - Crate Isolation: The procedural macro must reside in a separate crate from the code that consumes it due to the compiler needing to compile the macro as a compiler plugin before it can parse the consuming crate’s AST.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More





