Escaping braces in Rust format strings
Curly braces are syntax inside Rust format strings, so literal braces must be escaped. Double the character: {{ emits {, and }} emits }.
let name = "rust";
assert_eq!(format!("{{{name}}}"), "{rust}");Literal braces
Section titled “Literal braces”The doubled pairs are escapes in the format string itself. They do not add another formatting argument, and Rust parses them as literal text around any real replacement fields.
That makes a pattern such as {{{name}}} valid. Read it as three parts: {{ for a literal opening brace, {name} for the captured value, and }} for a literal closing brace.
Why a single brace fails
Section titled “Why a single brace fails”A lone opening or closing brace is interpreted as formatting syntax. If it cannot form a valid replacement field, Rust rejects the format string at compile time.
This is useful failure behavior. You do not need a runtime escape pass, and malformed formatting syntax does not wait until production input reaches the code.
JSON-looking and template-looking output
Section titled “JSON-looking and template-looking output”Escaped braces are useful when you need output that visually contains object or template delimiters. They only solve literal brace syntax, though. They do not serialize data or make a string valid JSON.
For actual data serialization, use a serializer rather than building a structured format manually with format!.