Sub topic 12
Width and precision chosen at run time
This chapter assumes you can read a format string with a literal width such as {:8} or {:.2}. It also assumes you know that println! and format! take the same format syntax. Here you will learn to take the width or precision from a variable or an argument, so that the layout can depend on your data.
Why literals are not always enough
A literal width like {:<10} is fixed when you write the code. That works for a fixed report layout. It fails when the longest name in a table is only known after you have read the data, or when the user chooses how many decimal places to show.
Rust lets the width and the precision be values instead of literals. You mark them with a $ suffix or with a *.
Naming the width or precision with `$`
Put an argument name, or a position number, directly before a $. The compiler reads that argument as the width or precision.
fn main() {
let pi = 3.14159265_f64;
let width = 10;
let prec = 3;
println!("[{:width$.prec$}]", pi);
println!("[{:>1$}]", "x", 4);
println!("[{:.*}]", 2, pi);
}This prints:
[ 3.142]
[ x]
[3.14]The three lines use three different forms:
{:width$.prec$}captures the variableswidthandprecfrom the surrounding scope, the same way{name}captures a value. The width is 10 and the precision is 3.{:>1$}takes its width from positional argument 1, which is4. The value printed is argument 0,"x", right-aligned in 4 columns.{:.*}takes two arguments in order. The first is the precision (2) and the second is the value to print (pi).
You can also pass the width as a named argument at the call site:
fn main() {
println!("[{:>w$}]", "hi", w = 6);
}This prints [ hi].
Summary of the forms
| Syntax | Where the number comes from |
|---|---|
| `{:8}` | A literal in the format string |
| `{:w$}` | A named argument `w = ...`, or a variable `w` in scope |
| `{:1$}` | Positional argument number 1 |
| `{:.p$}` | Precision from `p` |
| `{:.*}` | Precision from the next positional argument, then the value from the one after it |
| `{:w$.p$}` | Both from names |
How the arguments are matched
The .* form is the one that surprises people. It consumes two positions from the implicit counter that {} placeholders also use. After it, a plain {} continues from the next position.
fn main() {
println!("{:.*} {}", 2, 3.14159, "x");
}This prints 3.14 x. The 2 is the precision, 3.14159 is the value, and "x" goes to the plain {}.
The $ forms do not move that counter. An argument that is referenced as a width through 1$ is still free to be printed by its own placeholder. The compiler also checks that every argument is used somewhere. An argument that is never referenced is a compile error.
The type must be `usize`
A width or precision taken from an argument must have type usize. An i32 variable is rejected at compile time with a mismatched-types error. A literal such as let width = 10; works because the compiler infers usize from how you use it. If your number arrives as another integer type, convert it first with as usize or usize::try_from(n). The try_from form is the safer choice for values that can be negative.
What precision means for each type
Precision has a different meaning depending on the value being printed.
| Value type | Effect of precision |
|---|---|
| Floating point | Number of digits after the decimal point, with rounding |
| String or `&str` | Maximum number of characters; longer text is cut off |
| Integer | Ignored |
Width never truncates. If the value is longer than the width, the full value is printed and the layout grows.
Both width and precision count characters (Unicode scalar values), not bytes. A computed width should therefore come from chars().count(), not len(). The next example does this for a table:
fn main() {
let rows = [("apple", 1.5), ("banana", 12.25), ("kiwi", 0.333)];
let w = rows.iter().map(|(name, _)| name.chars().count()).max().unwrap_or(0);
for (name, price) in rows {
println!("{name:<w$} | {price:>8.2}");
}
}This prints:
apple | 1.50
banana | 12.25
kiwi | 0.33The column is as wide as the longest name, whatever the data contains. Add a longer fruit to the array and every row adjusts.
A configurable decimal count
Precision from a function parameter is a common use. This helper lets the caller choose:
fn show(value: f64, decimals: usize) -> String {
format!("{value:.decimals$}")
}
fn main() {
for d in 0..=3 {
println!("{}", show(2.71828, d));
}
}The output is 3, 2.7, 2.72, 2.718, one per line. The loop variable d is a usize because it is passed to a usize parameter.
Precision also works with Debug. In {:.1?} the ? comes after the precision, and the precision is applied to each float inside the collection:
fn main() {
let prec = 1;
println!("{:.prec$?}", vec![1.26, 2.0]);
}This prints [1.3, 2.0].
Centering with a computed width
Fill and alignment are literal characters. Only the numbers can be dynamic. The fill character itself cannot come from a variable. A banner helper shows the two parts together:
fn banner(text: &str, width: usize) {
println!("{:=^width$}", format!(" {text} "));
}
fn main() {
banner("Report", 20);
}This prints ====== Report ======. The = is the literal fill, ^ centers, and width$ is the run-time number.
Reading these values in your own types
When you implement Display for your own type, the run-time width and precision arrive in the formatter in the same way as literals. You can read them with f.width() and f.precision(), which both return Option<usize>. Most of the time you do not need to. A later chapter shows Formatter::pad, which applies them for you.
Common errors
- Mismatched types: the width variable is
i32oru32. Convert it tousize. - Argument never used: a number such as
4inprintln!("{:>1$}", "x", 4)is fine because it is referenced. Remove the1$and the compiler reports an unused argument. - Wrong argument order with
.*: the precision comes first, then the value. Swapping them gives a type error for a float used as a precision. - Misaligned columns with non-ASCII text: using
len()counts bytes. Usechars().count(). Even then, characters that occupy two terminal columns can still look uneven.
Exercise
Write a function row(label: &str, value: f64, label_width: usize, decimals: usize) -> String that returns the label left-aligned in label_width columns, then : , then the value right-aligned in 8 columns with decimals digits after the point. What does row("pi", 3.14159, 5, 2) return?
Show answer
Use format!("{label:<label_width$} : {value:>8.decimals$}"). For the call shown, the label pi is padded to pi (5 columns), and the value 3.14 is padded to 3.14 (8 columns), so the result is pi : 3.14.