Rust Format Parameters
Format parameters are numbers taken from other arguments to shape a slot. The program can then choose the width or precision while it runs.
Width from another argument
End the width with $ and name the argument that holds it. Here the value is the first argument and the width is the second:
println!("[{:1$}]", "x", 5);The value need not come first
The numbers count every argument, the value included. This slot prints argument 1, with a width taken from argument 0:
println!("[{1:0$}]", 6, "ab");Precision after a $
Precision takes a $ too, by number or by name:
println!("[{:.1$}]", 3.14159, 2);
println!("[{:.prec$}]", 3.14159, prec = 2);Catch a variable by name
A variable already in scope can serve as the parameter — no extra argument is needed:
let w = 6;
println!("[{:>w$}]", 42);
let p = 3;
println!("[{:.p$}]", 3.14159);The star takes the next argument
.* is the older spelling. The slot uses two arguments. The next one is the precision. The one after it is the value:
println!("pi is {:.*}", 3, 3.14159);Parameters inside inline slots
Parameters work in {name} slots too. This one trims a word to 3 letters and right-aligns it in 8:
println!("[{word:>8.*}]", 3, word = "1234.56");Example
fn main() {
let pi = 3.14159265;
let e = 2.71828182;
let w = 8;
let p = 2;
println!("pi = [{pi:>w$.p$}]");
println!("e = [{e:>w$.p$}]");
println!("pi to 4 places = {:.*}", 4, pi);
}Key points
- A $ parameter must hold a usize: widths and precisions are counts, so a negative or fractional parameter will not compile
- Reading a $ parameter does not use up the "next argument" place.
- Plain {} slots keep counting as if the parameter was not there
- Use parameters when the size is only known at run time.
- A table column as wide as its longest entry is the classic case
In this example, one spec does all the work twice. {pi:>w$.p$} reads the value from the variable pi. It takes the width from w and the precision from p. So pi prints right-aligned in 8 places, with 2 digits after the point: 3.14 with four spaces before it. The same spec then prints e the same way, 2.72. The spec never hard-codes the settings — only where they live. The last line uses the star form: 4 is the precision and pi is the value, giving 3.1416. Change w or p once, and every line reshapes itself.
Note
Every argument you pass must be used by some slot or parameter.
An argument nothing touches is a compile error — Rust refuses to let you pass data that goes nowhere.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does format!("{:.*}", 2, 3.14159) return?