Sub topic 12
Width and precision chosen at run time
This chapter assumes you know the basic specifiers {:8}, {:<8}, and {:.2} from the earlier chapters. Here you will supply the width and precision as values instead of typing them into the format string.
Why run-time values help
A fixed width such as {:10} breaks when data changes. If one name is longer than 10 characters, the columns no longer line up. Rust lets the width or precision come from a variable or an argument, so you can compute it from your data.
The `$` suffix
Put an argument name or position followed by $ where the number would go.
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]Each line uses a different form:
width$andprec$read the variableswidthandprecfrom the surrounding scope.1$means "use positional argument 1 as the width". Argument 0 is"x"and argument 1 is4, so the width is 4..*takes two arguments from the list. The first is the precision and the second is the value to print. That is why2comes beforepi.
Building a table from data
The most common use is sizing a column from the longest entry.
fn main() {
let rows = [("apple", 1.5), ("watermelon", 12.25), ("fig", 0.333)];
let name_width = rows.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
for (name, price) in rows {
println!("{name:<name_width$} | {price:>8.2}");
}
}The output is:
apple | 1.50
watermelon | 12.25
fig | 0.33The column width is 10 because watermelon has 10 bytes. Note that len() counts bytes, not characters, so names with accented letters or emoji can misalign.
Precision on strings
For floating-point numbers, precision is the number of digits after the decimal point. For strings, it is the maximum number of characters, and longer text is cut off. For example, {:.3} applied to "abcdef" prints abc. Integers do not accept a precision.
Common errors
- Wrong type. The width and precision must be
usize. A variable declared aslet width: i32 = 8;fails to compile. Convert it withwidth as usize, or leave the variable untyped so the compiler infersusize. - Miscounted
.*arguments..*consumes two positional arguments. If you write{:.*}with only the value, the compiler reports a missing argument. - Unused arguments. Every argument must be used. An argument that is only a width, as in
{:>1$}, counts as used.
Exercise
Write a println! call that prints the value 2.71828 (an f64 named e) with a precision stored in a usize variable named digits, right-aligned in a field 12 characters wide stored in field. What does it print when digits is 4 and field is 12?
Show answer
println!("[{e:>field$.digits$}]"); prints [ 2.7183]. The number takes 6 characters, so 6 spaces of padding fill the 12-character field.