Rust Formatting Text
Text formatting is the shaping of text inside a format slot. Precision means a character limit for text.
Text hugs the left, numbers hug the right
The same slot, the same width — the default side differs by type:
println!("[{:6}]", "hi");
println!("[{:6}]", 42);Arrows aim the text
The > and ^ signs aim numbers in a slot. On text they work the same way:
println!("[{:>6}]", "hi");
println!("[{:^7}]", "hi");Fill with any character
Put a fill character before the arrow to pad with it instead of spaces:
println!("[{:*>6}]", "hi");Precision cuts text short
On text, precision is a cap counted in characters. Even emoji are cut by whole characters, never by bytes:
println!("[{:.3}]", "héllo");
println!("[{:.2}]", "💖💖💖");Width and precision together
Cut first, then pad. The width may come from a variable with the $ form, just as in the numbers lesson:
println!("[{:>8.3}]", "abcdefgh");
let w = 6;
println!("[{:>w$}]", "hi");Debug shows text as code
{:?} wraps text in quotes and spells out escapes — handy when invisible characters are the bug. {:#?} changes nothing for one piece of text, but spreads a collection over many lines:
println!("{:?}", "say \"hi\"\nbye");
println!("{:?}", ["a", "b"]);
println!("{:#?}", ["a", "b"]);Example
fn main() {
let rows = [("ada", 36), ("grace", 45), ("ferris", 5)];
for (name, age) in rows {
println!("{:<8} {:>3}", name, age);
}
println!("{:.4}...", "longname");
println!("[{:>6}]", "hi");
}Key points
- Width counts characters for text: {:6} on "hi" makes a field 6 characters wide
- Use {:.3} on text to cap it at 3 characters.
- Longer text is cut short.
- The count is characters, never bytes.
- So a multi-byte letter is never cut in half.
- Take the precision from a value too, ending its name with $: {:.prec$} uses the number stored in prec
- Width and precision combine: {:>8.3} first cuts the text to 3 characters, then pads the result to width 8
- Use {:?} on text to see it as code.
- It adds quotes.
- It shows escapes like \n as two characters.
- That is ideal for spotting hidden spaces and new lines.
In this example, a small table prints names and ages. The name slot {:<8} left-aligns each name in a field 8 characters wide. The age slot {:>3} right-aligns each age in a field of 3. Together they make straight columns. That is the everyday job of width. The {:.4} line caps "longname" at 4 characters, printing long followed by three dots the code added itself. The last line right-aligns "hi" in width 6 on purpose. Text only hugs the left when you do not say otherwise.
Note
{:.3} is digits after the point for a float, but a character cap for text.
The slot reads the value's type and picks the meaning.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does {:.3} do to the text "abcdef"?