Rust Notes: Macros
Published: 2025-03-25
Intro
Macros are Rusts way to implement metaprogramming. Metaprogramming is code that uses code as a data input to write other code.
Rust Macros run at compile time and generate the output code (structs, functions, etc..)
Procedural Macros
There are 3 kinds of Proceedural Macros:
- Derive
- Attribute
- Function-Like
Derive
Derive Macros as defined with the #[derive] syntax, and are attached to Enums, Structs and Unions by 'decorating' them.
Derive Macros take the decorated type as an input and implements functions and/or traits to extend the inputs functionality. The original code is not modified, new code is generated and as the output.
#[derive(Debug)] // Decorated Struct
struct Stuff {}
Attribute Macros
Attribute Macros can be placed on Structs, Enums, Unions, Trait Definitions and Functions.
Attribute Macros transform the item the are decorating.
The following Attribute Macro, converts the main fuction to setup an async runtime with Tokio.
#[tokio::main]
async fn main() {}
Function Like
Function Like macros, look like function and are invoked with the ! operator. They take the input and generate new code as an output.
Like a function, they can be called throughout your code.
println!("Stuff and Things");
Declarative Macros
Outro
Links
https://doc.rust-lang.org/book/ch20-06-macros.html
https://doc.rust-lang.org/reference/macros-by-example.html
https://doc.rust-lang.org/reference/macros.html
https://livebook.manning.com/book/write-powerful-rust-macros/