Procedural macro
A procedural macro is a Rust macro implemented as a program that transforms an input token stream into generated code during compilation.
Write Powerful Rust Macros
A procedural macro is a Rust macro implemented as code that receives a token stream and programmatically produces another token stream.
- How it is used
- Generates compiler-checked Rust code when declarative macros cannot express required transformations.
- How deep it goes
- Explains TokenStream input and output, lexing, parsing, setup, testing, and expansion inspection without claiming full compiler internals.
- Examples
- Builds a Hello derive macro that adds behavior to struct Example through a macro library and consumer application.
- What you can do after
- Build it from scratch as a derive-macro library, test generated code, and inspect expansions with cargo expand.
Read how Write Powerful Rust Macros explains procedural macro →
Idiomatic Rust
A procedural macro is a Rust macro implemented as code that programmatically transforms a token stream into generated Rust code.
- How it is used
- Generates Rust code at compile time for language extensions and repetitive implementations, particularly derives.
- How deep it goes
- Works through raw token output and a derive implementation with parsed input and generics, but limits treatment to basics.
- Examples
- Demonstrates a greeting macro and a PrintName derive alongside its generated trait implementation.
- What you can do after
- Build a basic function-like macro or derive macro in a procedural-macro library crate.
Related concepts
- attribute macroincludes · An attribute macro is a compile-time procedural transformation attached to a language item that generates replacement or additional code.
- derive macroincludes · A Rust derive macro is an attribute that automatically generates implementations of specified traits or related functionality for a type.
- function-like macroincludes · A function-like macro is a macro invoked with function-like syntax that accepts token input and expands or transforms it into generated source.
- TokenStreamuses · TokenStream is a sequence of Rust source tokens used as input or output during procedural macro expansion and code generation.
- macrokind of · A macro is a named construct that expands or transforms source code, commands, or templates before or during execution.
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.

