Sub topic 4
Printing literal braces
This chapter covers how to print { and } as ordinary characters. It assumes you can write println! calls with {} placeholders, positional arguments, named arguments, and inline captured variables like {name}. You should also know that println!, format!, and write! all share one format-string syntax.
Why braces need escaping
In a format string, { starts a placeholder and } ends it. The compiler reads the string at compile time and looks for these markers. A brace you meant as plain text would be read as part of a placeholder, so Rust needs a way to say "this one is just a character."
Rust's way is to double the brace:
{{prints a single{.}}prints a single}.
fn main() {
println!("{{}} prints braces");
println!("a set looks like {{1, 2, 3}}");
println!("just an open brace: {{");
println!("just a close brace: }}");
}This prints:
{} prints braces
a set looks like {1, 2, 3}
just an open brace: {
just a close brace: }The text {{}} in the first line has no placeholder in it. It is two escaped braces side by side, so no argument is needed. Adding an argument to that line would be a compile error because the argument is never used.
Backslash does not work
Many languages escape special characters with a backslash. Rust does not do that here. The backslash is handled by the string literal, which runs before the format string is parsed. The string literal does not know \{ as an escape sequence, so this fails:
fn main() {
// Does not compile: unknown character escape `{`
println!("\{");
}The only escape for a brace in a format string is the doubled brace.
Mixing escaped braces with placeholders
The parser reads the format string from left to right. At each brace it checks whether the next character is the same brace. If it is, the pair becomes one literal brace. Otherwise the brace starts or ends a placeholder.
That rule explains a case that looks confusing at first, three braces in a row:
fn main() {
println!("{{{}}}", 5);
}This prints {5}. The parser splits {{{}}} into three pieces:
{{becomes a literal{.{}is a placeholder, filled with5.}}becomes a literal}.
The same rule works with named arguments, inline captures, and format specifiers:
fn main() {
let name = "x";
println!("{{{name}}}");
println!("{{{:>5}}}", 42);
println!("{{{0}, {1}, {0}}}", "a", "b");
println!("{{:?}} is the debug placeholder");
}This prints:
{x}
{ 42}
{a, b, a}
{:?} is the debug placeholderThe last line shows that anything between doubled braces is plain text. The :? there is not interpreted, because the braces around it were escaped.
A practical case: building JSON
Hand-built JSON is full of braces, so it is a common reason to need escapes. Reading "{{\"name\": \"{}\", \"age\": {}}}" from left to right, the format string breaks down like this:
fn main() {
let json = format!("{{\"name\": \"{}\", \"age\": {}}}", "Ada", 36);
println!("{json}");
}The output is {"name": "Ada", "age": 36}.
The ending {}}} is a placeholder followed by an escaped brace. The parser reads {} first, then }}.
For anything beyond a throwaway string, a serialization library such as serde_json is safer. It also escapes quotes inside values, and a plain format! does not.
Escaping inside a Display implementation
When you implement Display, the format string passed to write! follows the same rules. This is the usual place to meet escaped braces in real code, for example when printing a set-like type:
use std::fmt;
struct Pair {
a: i32,
b: i32,
}
impl fmt::Display for Pair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{{}, {}}}", self.a, self.b)
}
}
fn main() {
let p = Pair { a: 1, b: 2 };
println!("{p}");
}This prints {1, 2}. The write! macro uses the same format syntax as println!, so the escape rule is identical.
Where escaping applies
Escaping applies to any macro that takes a format string. That includes print!, println!, eprint!, eprintln!, format!, write!, writeln!, and the message forms of panic!, assert!, and unreachable!.
Two details are easy to get wrong.
First, raw string literals do not change the rule. A raw string such as r"{{" turns off backslash handling, but the format parser still runs afterward. You still write {{ for a literal brace.
Second, escaping only affects the format string, not the arguments. If a value contains braces, they print as they are:
fn main() {
let text = "{}";
println!("{}", text);
println!("{text}");
}Both lines print {}. Do not double braces in data that you pass as arguments. Doubling would change the data itself, and the format machinery would not remove the extra braces.
Common errors
| Mistake | What happens |
|---|---|
| A single `}` in the text, as in `println!("a } b")` | Compile error: unmatched `}` found. |
| A single `{` in the text, as in `println!("a { b")` | Compile error about an invalid format string. The parser sees an unfinished placeholder. |
| `println!("\{")` | Compile error from the string literal: unknown character escape. |
| `println!("{{}}", 5)` | Compile error: the argument is never used, because `{{}}` contains no placeholder. |
| `println!(text)` with a non-literal `text` | Compile error. The format string must be a string literal. Use `println!("{}", text)`. |
Because all of these are caught at compile time, none of them can panic in a running program. The compiler tells you the problem before the code ever runs.
Summary of rules
- Write
{{to print{and}}to print}. - Backslash does not escape braces in format strings.
- The parser reads left to right, so
{{{}}}is a literal brace, a placeholder, and a literal brace. - Escapes are needed in every macro that takes a format string, including raw-string formats.
- Arguments are never escaped. Braces inside values print as they are.
Exercise
What does println!("{{{}}} and {{{}}}", 1, "two"); print? Then write a format! call that produces the text {"id": 7} using the value 7 from a variable named id.
Show answer
The first line prints {1} and {two}. Each {{{}}} is an escaped open brace, a placeholder, and an escaped close brace. For the second part, use let id = 7; let s = format!("{{\"id\": {id}}}");. This gives {"id": 7}. The ending {id}} is a placeholder followed by an escaped close brace, so the parser reads {id} and then }}.
Exercise
Why does let t = "a {} b"; println!("{}", t); print a {} b while println!("a {} b") does not compile?
Show answer
In the first call, the braces are inside an argument, and arguments are never parsed as format strings, so they print unchanged. In the second call, the braces are in the format string itself. The {} is a placeholder with no argument to fill it, which is a compile error. To print those braces literally there, write println!("a {{}} b").