Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
A function takes values. A macro takes code (tokens) and produces
new code that is inserted at compile time. The ! in println!, vec!,
and assert_eq! marks a macro call.
fn main() {
println!("Hello, world!");
assert_eq!(6 + 4, 10);
}
macro_rules! is the main way to define macros in Rust. A macro is a series
of patterns and templates:
macro_rules! say_hello {
() => {
println!("Hello!");
};
}
fn main() {
say_hello!();
}
// → Hello!
! after say_hello — the ! belongs only to calls.() → template { println!("Hello!"); }: when arguments
match, the template is substituted.assert_eq!(6 + 4, 10); // parentheses
assert_eq![6 + 4, 10]; // square brackets
assert_eq!{6 + 4, 10}; // curly braces
All three are equivalent. Convention: parentheses for assert_eq!, square
brackets for vec!, curly braces for macro_rules! itself.
The Purpose of Macros
Macros are almost always convenience: they save typing by generating
recurring boilerplate — such as vec! instead of a manual Vec::new() plus
push calls. But they can also do things functions cannot: evaluate expensive
arguments only on demand (like assert! formats the error text), or
generate operator syntax.
Check: How does a macro differ from a function?
Answer: A macro takes code and produces new code
A macro treats tokens (code) as input and expands to new code at compile time. Functions work with values at runtime.
⚠ Common mistake: Calling the macro like a function (
say_hello()) gives "cannot find functionsay_helloin this scope" — along with a note about the macro of the same name. The!isn't a style detail, it's part of the call.
Takeaways:
Inside a pattern, $name:type captures a piece of the argument. $ marks a
metavariable. A common type is expr (an expression):
macro_rules! print_twice {
($v:expr) => {
println!("{v} {v}");
};
}
fn main() {
print_twice!(2 + 3); // 5 5
}
The metavariable $v holds the expression 2 + 3 and is substituted at both
places in the template — so the expression is evaluated twice.
expr — an expression (2 + 3, foo(), x)ident — an identifier (my_var)ty — a type (Vec<String>)tt — a single token (or token tree): the universal building blockliteral — a literal (42, "text")pat — a patternmacro_rules! print_twice {
// Pattern: Template:
($v:expr) => { println!("{v} {v}"); };
}
Rust expands macros very early during compilation: the compiler reads from start to finish, defining and expanding macros as it goes. So a macro must be defined before its first call — unlike functions, which may live anywhere in a crate.
Expressions are evaluated multiple times
An expr that appears multiple times in the template is also evaluated
multiple times. This is dangerous if the expression is expensive or has
side effects:
print_twice!(consume()); // is called TWICE!
Rust macros don't "bind values" like functions — they insert the expression textually. Be aware of this with metavariables.
Check: What happens when a metavariable $v appears twice in the template?
Answer: The expression is evaluated twice
Macros insert the expression textually; a $v in two places means evaluation in two places. Functions, by contrast, bind a value.
⚠ Common mistake:
($v: String)doesn't compile — after the colon comes a fragment specifier likeexpr,ty, orident, not a concrete data type. The compiler reports "expected fragment specifier"; whether the captured code fits the target type is only checked after expansion.
Takeaways:
A macro like vec! must handle an arbitrarily long comma-separated list.
For that there is the repetition syntax:
$($x:expr),*
It matches zero or more expr, separated by commas. In the template, the
repetition is written $(...).
macro_rules! my_vec {
($($x:expr),*) => {{
let mut v = Vec::new();
$(v.push($x);)*
v
}};
}
fn main() {
let numbers = my_vec!(1, 2, 3, 4);
println!("{:?}", numbers); // [1, 2, 3, 4]
}
// → [1, 2, 3, 4]
What happens here:
$($x:expr),* matches the list of arguments.$(v.push($x);)* repeats the push call once per argument:
v.push(1); v.push(2); v.push(3); v.push(4);The standard library implements three vec! forms — all from patterns:
let empty: Vec<i32> = vec![]; // empty pattern
let buffer = vec![0u8; 1000]; // x; n → Repeat
let noodles = vec!["udon", "ramen", "soba"]; // list
A macro tries its rules in order. If none matches, it's an error — which
you can make friendlier with compile_error!.
$(...), in detail*
Repetition has two parts:
$(PATTERN),* — in the pattern: matches a comma-separated list each of
whose elements matches PATTERN. * means "0 or more", + "1 or more".$(...)* — in the template: repeats the contained code for each captured
element.macro_rules! log_all {
($($arg:expr),*) => {
$(eprintln!("{arg}");)*
};
}
Check: What does the pattern (x:expr),*) match?
Answer: A comma-separated list of expressions (even empty)
x:expr ),* matches a comma-separated list of arbitrary expressions, even empty. In the template, $(...)* repeats the code for each element.
⚠ Common mistake:
($($x:expr),*)rejects a trailing comma — the callmy_vec!(1, 2, 3,)fails with "no rules expected token,". An extra pattern like($($x:expr),* $(,)?)swallows the stray comma, exactly asvec!itself does.
Takeaways:
Some macros are hardcoded in rustc and couldn't be built with macro_rules!
alone:
file!() — the file containing the call (as a string literal)line!() — the current line number (u32, starting at 1)column!() — the current column (u32, starting at 1)module_path!() — the Rust module path like "fernlib::fronds"stringify!(...tokens...) — the tokens as a string literalconcat!(str0, str1, ...) — concatenates stringscompile_error!("msg") — aborts compilation with a messagefn main() {
let s = stringify!(1 + 2);
println!("{s}"); // prints: 1 + 2
// macro calls are NOT expanded:
let t = stringify!(line!());
println!("{t}"); // prints: line!()
}
assert! uses stringify! to produce an error message that includes the
original code of the assertion.
Macros otherwise give cryptic errors like "no rules expected". With a pattern that catches common user mistakes, your macro provides a clear message:
macro_rules! need_two {
($a:expr, $b:expr) => { $a + $b };
($($x:expr),*) => {
compile_error!("need_two! expects exactly two arguments")
};
}
Where does file!/line! get its location?
file!, line!, and column! report the location of the first macro call.
If macro A calls macro B in a different file, file!() reports the file of the
first call — the user's, not the macro definition's.
Check: What does stringify!(line!()) expand to?
Answer: The string "line!()"
stringify! does not expand macro calls in its argument; it turns the tokens line!() into the string "line!()".
⚠ Common mistake:
stringify!(1 + 2)yields the text"1 + 2", not"5"— the macro quotes tokens, evaluates nothing, and doesn't expand inner macros either. If you need a value as text, format it at runtime withformat!.
Takeaways:
A macro glues together code from different scopes. Two questions:
Local variables and arguments that your macro introduces internally are hygienic: they cannot collide with the caller's variables.
macro_rules! swap {
($a:expr, $b:expr) => {{
let tmp = $a;
*$a = *$b;
*$b = tmp;
}};
}
fn main() {
let mut x = 1;
let mut y = 2;
let mut tmp = 999; // no conflict with the internal tmp!
swap!(&mut x, &mut y);
println!("x={x} y={y} tmp={tmp}"); // x=2 y=1 tmp=999
}
The internal tmp in the macro does not disturb the caller's tmp — that's
exactly what hygiene is for.
Types, functions, modules, and other items that your macro references are
resolved in the calling scope. That's why standard macros like to write
::std::vec::Vec instead of Vec — so they always hit the right namespace,
even if the caller defined its own Vec.
The rule in one sentence
Local variables & arguments: hygienic (no conflict with the caller).
Items & other names: not hygienic (resolved in the calling scope). For
robust macros: use paths like ::std::....
Check: What happens when a macro internally introduces a var tmp and the caller also has tmp?
Answer: Internal variables are hygienic — no conflict
Thanks to hygiene, variables introduced locally inside a macro never collide with same-named variables of the caller. Items like types, however, are not hygienic.
⚠ Common mistake: Hygiene cuts both ways: a variable the macro introduces internally with
letis invisible to the caller — touching it afterwards gives "cannot find value in this scope". Values only leave the macro through the expression it expands to, not through side doors.
Takeaways:
A macro defined with macro_rules! is visible from its definition onward in
the same module. To expose it, write #[macro_export]:
// lib.rs
#[macro_export]
macro_rules! print_all {
($($arg:expr),*) => {
$(println!("{arg}");)*
};
}
With #[macro_export] the macro lands on the crate root and is reachable from
outside as my_crate::print_all!. Within a crate, use use crate::... (or
#[macro_use] across crate boundaries).
Macros are often hard to debug because you can't see the expanded form. Nightly offers two experimental helpers:
trace_macros!(true) — prints each macro expansionlog_syntax!() — prints its arguments without expandingcargo expand (external tool) — shows the fully expanded codeBesides declarative macro_rules! macros, there are procedural macros
(procedures that run at compile time and transform tokens):
#[derive(...)] — can automatically generate e.g. Debug or Clone#[test] or web-router annotationsmacro_rules!, but with full codederive(Serialize), derive(Deserialize) in Serde or #[tokio::main] are
well-known procedural macros in practice.
When macro, when function?
Rule of thumb: use a function when possible. Macros add complexity, are
typically visible only locally, and are harder to debug. Reach for a macro when
you need true metaprogramming: generating list syntax, boilerplate (derive),
or lazy evaluation. Otherwise a plain function is simpler, more readable, and
testable.
Check: What does #[macro_export] do for a macro_rules! macro?
Answer: It exports the macro out of the module/crate
#[macro_export] puts the macro on the crate root so other crates can use it as my_crate::macro!.
⚠ Common mistake:
#[macro_export]exports to the crate root, not to the module where the macro is defined —use my_lib::utils::print_all;fails with "unresolved import". The correct path isuse my_lib::print_all;, because that's where the macro actually lives for outsiders.
Takeaways:
You now build your own declarative macro that combines several abilities from this module:
run_and_catch! with macro_rules!.$v:expr).panic!, catch the error and return
Err; otherwise return Ok.stringify!) to print the affected line of code
in plain text on error.This tests pattern matching, metavariables, and built-in macros — and you'll
briefly think about hygiene because you use catch_unwind with UnwindSafe.
Recipes from this module
macro_rules! name { (PATTERN) => { TEMPLATE }; }$v:expr$($x:expr),* + $(...)*file!(), line!(), stringify!($v)compile_error!("...")Scenario: The repetition
⚠ Common mistake:
catch_unwinddemands anUnwindSafeclosure — if it captures a mutable reference (say, your result&mut), the compiler reports "may not be safely transferred across an unwind boundary". Wrapping the closure inAssertUnwindSafe(...)explicitly tells it you accept that risk.
Takeaways:
Course navigation: ← Module 18 · All 27 modules · Module 20 →