Common Standard Macros
stringify!
The stringify! macro converts any sequence of valid Rust tokens into a &'static str literal at compile time without evaluating or type-checking the tokens.
How stringify! Works
const EXPR_TEXT: &'static str = stringify!(1 + 2 * 3);
// Evaluates to the string literal `"1 + 2 * 3"`, NOT `"7"`!
- No evaluation: Expressions, function calls, or even undefined identifiers passed inside
stringify!(...)are never executed or resolved as variables—they are simply serialized into their token representation. - Token normalization: Because
stringify!operates on lexed tokens rather than raw source characters, comments are stripped and whitespace may be normalized by the compiler.
fn main() {
// Even though `non_existent_fn` does not exist, `stringify!` only lexes its tokens:
let raw_code = stringify!(non_existent_fn(x + 1, "hello"));
println!("Stringified tokens: {raw_code}");
}
Stringified tokens: non_existent_fn(x + 1, "hello")
Building Diagnostic and Reflection Macros with stringify!
Standard library macros such as assert!, dbg!, and custom macro_rules! definitions use stringify! to print the exact source expression alongside its evaluated value, or to implement name-introspection methods for enums and structs:
macro_rules! check_positive {
($expr:expr) => {{
let val = $expr;
if val > 0 {
println!("PASS: `{}` == {val} (> 0)", stringify!($expr));
} else {
println!("FAIL: `{}` == {val} (expected > 0)", stringify!($expr));
}
}};
}
fn main() {
let base = 10;
check_positive!(base * 3 - 5);
check_positive!(base - 25);
}
PASS: `base * 3 - 5` == 25 (> 0)
FAIL: `base - 25` == -15 (expected > 0)