Generate a pattern, keep it readable.
Recognize macro expansion and build a small macro_rules tool.
01 Understand the contract
Macros operate on token patterns before normal type checking of the expanded code. macro_rules! is useful for small repeated syntactic patterns such as constructing a collection, while derive macros generate trait implementations. A function should remain your first choice when ordinary typed parameters express the problem. Macro expansion errors can point into generated code, so keep macro interfaces narrow. The ! distinguishes a macro invocation such as vec! or println! from a function call.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
macro_rules! labels {
($($item:expr),* $(,)?) => { vec![$($item.to_string()),*] };
}
fn main() {
let values = labels!["build", 42, true];
println!("{values:?}");
}["build", "42", "true"]
- 1
The repetition accepts comma-separated expressions.
- 2
Each expression is converted to String.
- 3
The optional final comma is supported explicitly.
cargo run -p lesson_macros03 Mind the boundary
04 Your next build
Create a macro that produces a pair of independently supplied expressions, then test it.
Reveal one possible solution +
macro_rules! pair {
($a:expr, $b:expr) => {
($a, $b)
};
}
fn main() {
assert_eq!(pair!(2 + 1, "ready"), (3, "ready"));
}05 Check your reasoning
When is a normal function preferable to a macro?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.