Macros and unsafe boundaries.
Understand code generation and where the programmer must supply a safety proof.
The idea behind the syntax.
A macro transforms Rust syntax into more Rust syntax before ordinary type checking continues. Declarative macros match patterns and expand templates; procedural macros operate on token streams and can derive code or modify an item. They can reduce repeated structure, but generated code still needs to be understandable to readers and debuggable when compilation fails.
Unsafe Rust allows a small set of operations the compiler cannot verify through its usual safety rules, such as dereferencing a raw pointer or calling an unsafe function. It does not turn off all checks inside the block. The programmer takes responsibility for the extra invariants that make the operation sound. A safe wrapper is valuable only if it truly enforces those invariants for every caller.
What Rust is checking.
A macro can accept syntax that a function cannot, or generate several related definitions. Prefer an ordinary function when it expresses the same idea clearly; the type checker can then show a simpler call boundary. When a macro is necessary, keep the public syntax predictable and explain what it expands into conceptually.
At an unsafe boundary, write down the exact proof obligation: valid pointer, correct alignment, initialized data, non-overlapping access, or a foreign function's contract. Keep the unsafe region small and test surrounding safe behavior, but remember that testing cannot prove every memory-safety invariant. The examples provide a way to read these powerful features without treating them as routine shortcuts.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Declarative macros
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.
macro_rules! labels {
($($item:expr),* $(,)?) => { vec![$($item.to_string()),*] };
}
fn main() {
let values = labels!["build", 42, true];
println!("{values:?}");
}["build", "42", "true"]
- The repetition accepts comma-separated expressions.
- Each expression is converted to String.
- The optional final comma is supported explicitly.
The boundary: Avoid macros that evaluate a side-effecting argument multiple times unless that behavior is documented and intended.
Unsafe & safe abstractions
unsafe enables specific operations such as dereferencing raw pointers or calling unsafe functions. It does not turn off the type system, ownership rules for ordinary references, or the need to uphold memory safety. The programmer must establish validity, alignment, lifetime, and aliasing requirements that the compiler cannot prove. Prefer a safe standard-library operation when one exists. When writing a safe wrapper around unsafe internals, document the invariant and test boundaries, while recognizing tests alone cannot prove absence of undefined behavior.
fn main() {
let values = [10, 20, 30];
let pointer = values.as_ptr();
// SAFETY: pointer comes from a live array; index 1 is in bounds,
// properly aligned, and no mutation conflicts with this read.
let second = unsafe { *pointer.add(1) };
assert_eq!(second, values[1]);
println!("{second}");
}20
- as_ptr obtains a raw pointer without dereferencing it.
- The unsafe block contains the operation requiring a manual proof.
- Ordinary indexing is the simpler safe choice for this example.
The boundary: An unsafe block is a claim that you upheld the rules, not runtime validation that you actually did.
Keep this model.
Macros change the code the compiler sees; unsafe changes who must prove certain memory rules. Both deserve a narrow, explicit boundary.