Macros in Rust
From the Rust cheat sheet ยท Macros & File I/O ยท verified Jul 2026
Macros
Write declarative macros with macro_rules! for code generation.
rust
// Built-in macros
println!("Hello, {name}!");
format!("x = {x}");
vec![1, 2, 3];
todo!("implement later"); // Compiles but panics at runtime
unimplemented!("not yet");
dbg!(expression); // Prints file:line and value
// Custom macro
macro_rules! say_hello {
() => { println!("Hello!"); };
($name:expr) => { println!("Hello, {}!", $name); };
}๐ก dbg!() prints the expression, file, and line โ perfect for quick debugging
โก todo!() lets you leave unfinished code that compiles โ panics if actually reached
๐ Macros use ! to distinguish them from functions โ vec![], println!(), assert_eq!()
๐ข The hashmap!{} macro pattern is a common way to create utility macros for collections
macrosmacro-rulesattributes