In Rust format strings, how do fill, alignment, width and precision combine, and why is `{price.cents}` rejected while `{price}` compiles?
answer
- order after the colon matters
- fill needs an alignment
- precision depends on the type
- captured names are identifiers only
basics
~20 sAfter the colon comes fill, alignment, sign, #, 0, width, precision and type, in that order. Since Rust 1.58 a placeholder may capture a bare variable name, but field access, method calls and arithmetic are rejected.
solid answer
~40 sA placeholder is `{argument:spec}`, and the spec runs fill, align (`<`, `^`, `>`), sign, `#`, `0`, width, `.precision`, type. Width is a minimum; strings default to left alignment and numbers to right. Precision is decimals for floats, a maximum length that truncates for strings, and is ignored for integers. Width and precision can come from `usize` arguments with `name$`. Since Rust 1.58 a placeholder can capture a variable in scope by name, as in `{amount:>9.2}`, but only a bare identifier: `{price.cents}` fails with "field access isn't supported" and `{total + 1}` is parsed as a bad spec. Bind the value to a local, or pass it positionally or as `cents = price.cents`.
code
rust · 14 linesfn main() {
let amount = 3.14159_f64;
let width = 9;
let item = "tea";
println!("[{amount:.2}]"); // precision: 2 decimals
println!("[{amount:>9.2}]"); // right-align in 9 columns
println!("[{amount:>width$.2}]"); // width taken from a variable
println!("[{amount:08.3}]"); // zero-pad after the sign
println!("[{item:*^7}]"); // fill '*', centred
println!("[{:5}] [{:5}]", 42, "ab"); // numbers right, strings left by default
println!("[{item:.2}]"); // precision on a string truncates
println!("{item:?}"); // Debug of a &str keeps the quotes
}go deeper
Recall the spec order after the colon, that width is a minimum, and that {name} captures a variable since Rust 1.58 but only a bare identifier.
Explain how precision differs for floats, strings and integers, the default alignments, the 0 flag after the sign, and width or precision taken from usize arguments with $.
Show you can build aligned report columns without allocation-heavy string juggling, and spot when a custom type silently ignores the width a caller passes.
Treat format-string conventions as house style: inline captured names for readability, explicit arguments for expressions, and lints such as Clippy's uninlined_format_args enforced consistently across crates.
## The shape of a placeholder Every placeholder in a Rust format string has the form `{argument:spec}`. The part before the colon picks **which value** to format; the part after picks **how**. The spec has a fixed order; pieces written out of order are either rejected or silently read as something else (`{:8>}` is fill `8` with no width, not width 8): 1. **fill** — any single character, only allowed when followed by an alignment; 2. **align** — `<` left, `^` centre, `>` right; 3. **sign** — `+` to always print the sign; 4. **`#`** — the alternate form (`{:#?}` pretty Debug, `{:#x}` with a `0x` prefix); 5. **`0`** — sign-aware zero padding for numbers; 6. **width** — the minimum number of characters; 7. **`.precision`** — decimals or a maximum length, depending on the type; 8. **type** — empty for `Display`, `?` for `Debug`, or `x`, `b`, `o`, `e` and friends. So `{amount:*^12.2}` means: format `amount`, centre it in at least 12 characters, pad with `*`, and keep 2 decimals. ## Width, fill and alignment - **Width is a minimum.** A value already longer than the width is printed in full; nothing is cut. - **Default alignment depends on the value.** The `std::fmt` docs: non-numerics default to left-aligned, numerics to right-aligned, both padded with spaces. So `format!("[{:5}] [{:5}]", 42, "ab")` gives `[ 42] [ab ]`. - **Centring is lopsided.** With an odd amount of padding the extra character goes to the right: `{:*^7}` on `"tea"` prints `**tea**`, and on `"ab"` it prints `**ab***`. - **The `0` flag** pads numbers with zeros *after* the sign and overrides fill and alignment: `{:08.3}` on `3.14159` gives `0003.142`, and `{:08}` on `-1` gives `-0000001`. - **Width can come from a value** with `$`: `{amount:>width$}` reads a `usize` called `width`, and `{:1$}` reads positional argument 1. ## Precision means different things per type | Value being formatted | What `.N` does | Example | |---|---|---| | `f32` / `f64` | digits after the decimal point, rounded | `{:.2}` on `3.14159` gives `3.14` | | `&str`, `String` | maximum characters; the text is truncated | `{:.2}` on `"tea"` gives `te` | | integers | ignored | `{:.2}` on `42` gives `42` | | your own type | whatever your impl does with `Formatter::precision()` | nothing, unless you read it | Precision can also come from an argument with `.N$`, `.name$` or `.*`, and must be a `usize`. ## Inline named arguments Since **Rust 1.58**, a placeholder may name a variable in scope directly: `println!("{amount:>9.2}")` instead of `println!("{:>9.2}", amount)`. It works in every macro that takes a format string — `format!`, `print!`, `write!`, `assert!` messages — and in `panic!` from the 2021 edition on. The rule is narrow on purpose: - only a **bare identifier** is captured — a local, a parameter, a constant in scope; - **field access is rejected**: `println!("{price.cents}")` fails with "invalid format string: field access isn't supported"; - **expressions are rejected**: `{total + 1}` is read as a spec and fails with "the `+` sign flag must appear after `:`"; - method calls such as `{name.len()}` are rejected too, with "expected `}`, found `.`". When you need an expression, bind it first (`let cents = price.cents;`), pass it positionally (`"{0}", price.cents`), or name it explicitly (`"{cents}", cents = price.cents`). Explicit named arguments and captured identifiers mix freely, and an explicit `name = value` wins over a variable of the same name. ## A worked line for the `Money` report Printing a two-column report of amounts usually combines all of the above: ```rust let width = 9; let amount = 3.14159_f64; println!("[{amount:>width$.2}]"); // [ 3.14] ``` `amount` is captured by name, `>` right-aligns, `width$` takes the column width from a variable, and `.2` rounds to two decimals. ## Common traps - Expecting `{:.2}` to round an integer — it is ignored for integral types. - Expecting `{:.3}` on a string to pad — it truncates. - Expecting your own `Display` type to honour width or precision automatically — it only does if the impl reads the `Formatter` or uses `Formatter::pad`, which belongs to a separate question about implementing `Display` well. - Passing an `i32` as `width$` — the argument must be a `usize`, and anything else is E0308, mismatched types.
- In Rust, what does `{:.2}` do to the integer 42 and to the string "tea"?For integral types precision is ignored, so `42` prints as `42`. For strings it is a maximum length, so `"tea"` is truncated to `te`. Only floats read it as a number of decimal places, rounded.
- How do you pass a column width held in a variable to a Rust format string?Use the `$` form: `{amount:>width$}` reads a variable or named argument called `width`, and `{:1$}` reads positional argument 1. The width argument must be a `usize`; an `i32` there is a type error.
- Can an explicit named argument and a captured variable of the same name coexist in one Rust `format!` call?Yes. The std::fmt docs say that a name not present in the argument list is looked up as a variable in scope; when `name = value` is listed, that explicit argument is used, so `format!("{x}", x = 5)` prints 5 even with a local `x` in scope.
- Writing {price.cents} or {total + 1} works because format strings take expressions.
- Precision {:.2} rounds integers to two decimal places.
- Precision on a string pads it out to that many characters.
- Width truncates a value that is longer than the width.
- Every value is left-aligned by default, numbers included.
Assumes Rust 1.99; capturing a bare identifier inside a format string has been stable since Rust 1.58, and panic! accepts it from the 2021 edition on.