A Rust Macro Example
Here is a comparable implementation of the previous custom syntax example written in Rust:
// Copyright 2026 Google LLC
// SPDX-License-Identifier: Apache-2.0
macro_rules! procedure {
($name:ident BEGIN $code:stmt; END) => {
fn $name() { $code }
};
}
macro_rules! expect {
($test:expr => OR DIE $message:literal) => {
if !$test {
panic!("{}", $message);
}
};
}
procedure! {
main BEGIN
for idx in 0..10 {
expect!(idx < 10 => OR DIE "Uh-Oh!");
};
END
}
Compared to C:
- Syntactic Safety: The input is structurally validated.
$codemust be a valid Rust statement and$namemust be a valid Rust identifier. - Hygiene: In
expect!, the testidx < 10is explicitly passed as an expression$test, rather than having the macro rely on a hidden, implicitly named local variable.
- Walk through how
procedure!defines a pattern that matches an identifier$name, followed by the literal tokenBEGIN, followed by a statement$code, a semicolon (which is required to separate a statement from the next syntactic construct) and then ourENDtoken. - Note that even though the syntax is custom, the Rust compiler ensures that the inputs to macros are well-formed before passing them to the macro.