Sub topic 4
Printing literal braces
This chapter assumes you know how {} placeholders work in println! and format!. It covers how to print the brace characters themselves.
Why braces need escaping
The characters { and } mark placeholders in a format string. The compiler reads them as syntax, so a lone brace is an error:
fn main() {
println!("{");
}This fails to compile with invalid format string: expected } but string was terminated. A lone } fails too, with unmatched } found. These are compile-time errors, so a bad brace never reaches run time.
Doubling the brace
To print a brace, write it twice. {{ produces { and }} produces }.
fn main() {
println!("{{}} prints braces; value = {{{}}}", 5);
}This prints:
{} prints braces; value = {5}The sequence {{{}}} can look confusing. The parser reads it from left to right in three pieces.
A practical case: JSON text
Escaping comes up most often when you build JSON or similar text by hand:
fn main() {
let id = 7;
let name = "Ferris";
let json = format!("{{\"id\": {id}, \"name\": \"{name}\"}}");
println!("{json}");
}This prints {"id": 7, "name": "Ferris"}. The outer {{ and }} are literal braces. The inner {id} and {name} are captured placeholders.
Common mistakes
- Escaping inside an argument. Only the format string is parsed.
println!("{}", "{}")prints{}with no doubling, because the argument is just data. - Expecting doubled braces to capture.
println!("{{name}}")prints{name}and never reads a variable calledname. - Passing extra arguments.
println!("{{}}", 5)fails to compile. The{{}}holds no placeholder, so the argument5is never used. - Using a variable as the format string. The first argument must be a string literal. Pass a variable as an argument instead:
println!("{}", text).
Exercise
Using a variable name that holds "Ferris", write a format! call that returns the text {"name": "Ferris"}, with the braces and quotes included.
Show answer
format!("{{\"name\": \"{name}\"}}"). The {{ and }} give the literal braces, \" gives the quotes, and {name} captures the variable.