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

More Rust tasks

Back to the full Rust cheat sheet