Rust for a C programmer · Reference

Formatting

Choose the arguments, their presentation, and where the resulting text goes.

Arguments

Examples below assume let name = "probe";.

FormExample
Next positional argumentprintln!("{}", name.len());
Numbered positionsprintln!("{1} {0}", "read", "open");
Capture a variableprintln!("{name}");
Name an expression's valueprintln!("{len}", len = name.len());

len = labels this formatting argument; it doesn't introduce a local variable. Write expressions after the template: {name.len()} is invalid. The Rust Book: placeholders · Optional lookup: named parameters.

Output or an owned result

UseEffect
println!("{name}")Standard output, then a newline.
eprintln!("{name}")Standard error, then a newline.
format!("{name}")Return a String; no newline added.

print! and eprint! omit the added newline. These macros borrow values for formatting. Evaluating an argument expression can itself move a value. Ownership example · Rust By Example: printing macros.

Width and numeric presentation

Put options after the colon. The examples use ASCII text and ordinary integers or floats.

Template and valueFormatted contents
"|{:<6}|", "cat"|cat |
"|{:>6}|", 12| 12|
"|{:^7}|", "cat"| cat |
"{:04}", 120012
"{:.2}", 3.53.50
"|{:8.2}|", 3.5| 3.50|

Width is a minimum and includes the whole formatted value. Longer values expand the field. Floating-point precision selects decimal places. The stored number is unchanged. Alignment here uses spaces; a fill character before the alignment changes the padding: "{:*>6}", 12 produces ****12.

Optional detailed lookup: width, fill and alignment, and precision. For terminal tables with non-ASCII text, visible column width needs additional care.

Hex, binary, braces, and debugging

ExampleOutput
println!("{:x} {:X} {:#x}", 42, 42, 42);2a 2A 0x2a
println!("{:b}", 10);1010
println!("{{status}} = {}", 7);{status} = 7
println!("{} / {:?}", "cat", "cat");cat / "cat"
println!("{:?}", [1, 2, 3]);[1, 2, 3]

{{ and }} print literal braces. {} requests Display; {:?} requests Debug. These are traits: named capabilities a type can implement. Display is for ordinary presentation; Debug is for inspecting values, often including quotes or structural punctuation. {:#?} requests a more spread-out Debug layout. We'll implement these traits later.

The Rust Book: Debug formatting · Rust By Example: number bases · Optional lookup: escaping braces.

Compiler checks

The usual template is a string literal. Rust checks its placeholders and whether each argument supports the requested formatting. These lines are deliberately invalid:

println!("{} {}", 7);       // Missing argument.
println!("{:x}", "cat");    // Text has no hexadecimal formatting implementation.
println!("{name.len()}");   // A method call is not a placeholder name.

Try one at a time with cargo check, then remove it. A String containing "{}" cannot replace the literal template in these calls. Formatting checks in Rust By Example.