A derive macro is a type of procedural macro in Rust that automatically generates and appends code to structs, enums, or unions at compile time. Unlike attribute macros, derive macros do not modify or consume the original item; they strictly append new Abstract Syntax Tree (AST) nodes to the module scope alongside the annotated item.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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.
Master Rust with Deep Grasping Methodology!Learn More





