Sub topic 9
Width, fill, and alignment
This chapter assumes you can write println! calls with {} placeholders and know the difference between Display ({}) and Debug ({:?}). Here you will learn how to make output occupy a fixed number of characters. That is the basis for aligned columns, headers, and simple tables.
The shape of the spec
Everything after the colon in a placeholder is the format spec. The first part of it is [[fill]align] followed later by width:
{ : [fill] [align] ... [width] ... }widthis the minimum number of characters the output should occupy.alignis one of<,^, or>.fillis the character used to pad. It defaults to a space.
The other parts (sign, #, 0, precision, type) come in later chapters. They sit between align and width or after it, so you can combine them with what you learn here.
| Symbol | Meaning |
|---|---|
| `<` | Align left. Padding goes on the right. |
| `^` | Center. Padding goes on both sides. |
| `>` | Align right. Padding goes on the left. |
Setting a width
A width alone pads the value up to that many characters.
fn main() {
println!("[{:6}]", "ab");
println!("[{:6}]", 42);
println!("[{:6}]", 'x');
println!("[{:6}]", true);
println!("[{:3}]", "abcdef");
}This prints:
[ab ]
[ 42]
[x ]
[true ]
[abcdef]Two rules show up here.
- The default alignment depends on the type. Strings,
char, andboolalign left. Numbers align right. - Width is a minimum, never a maximum.
"abcdef"is longer than 3, so it prints in full. To cut a string short you need precision, such as{:.3}, which yieldsabc.
Choosing alignment and fill
Add an alignment character to override the default. Put a fill character before it to replace the space.
fn main() {
println!("[{:<8}]", 7);
println!("[{:>8}]", "ab");
println!("[{:^8}]", "ab");
println!("[{:^7}]", "ab");
println!("[{:*>6}]", 42);
println!("[{:-<6}]", "ab");
println!("{:─^20}", " Report ");
}Output:
[7 ]
[ ab]
[ ab ]
[ ab ]
[****42]
[ab----]
────── Report ──────Look at the two centered lines. When the padding cannot be split evenly, the extra character goes on the right. With width 7 and "ab" there are 5 padding characters, so you get 2 on the left and 3 on the right.
The fill can be any single character, including a non-ASCII one like ─. A fill is only recognized when an alignment character follows it. A spec like {:*6} is a compile error, because * is not an alignment and is not a valid part of the spec in that position.
The following diagram shows how the formatter decides what to emit.
Counting characters, not bytes
Width counts Unicode scalar values (what Rust calls char). It does not count bytes, and it does not measure how wide the text looks on screen.
fn main() {
println!("[{:>6}]", "héllo");
println!("[{:>6}]", "日本");
}[ héllo]
[ 日本]"héllo" is 6 bytes but 5 characters, so one space of padding is added. "日本" is 2 characters, so four spaces are added. Many terminals draw those two characters double-wide, so the right edge will look uneven. Rust's standard formatting does not account for display width. If your columns must line up with East Asian text or emoji, you need a crate that measures display width.
Building a small table
Combining the pieces, you can print a table with a header, a rule line, and aligned rows. An empty string with a fill character is a handy way to draw the rule.
fn main() {
let rows = [("apple", 3, 0.5), ("watermelon", 12, 3.25), ("fig", 100, 12.0)];
println!("{:<12}|{:^6}|{:>8}", "item", "qty", "price");
println!("{:-<12}+{:-^6}+{:->8}", "", "", "");
for (name, qty, price) in rows {
println!("{:<12}|{:^6}|{:>8.2}", name, qty, price);
}
}This prints:
item | qty | price
------------+------+--------
apple | 3 | 0.50
watermelon | 12 | 3.25
fig | 100 | 12.00The widths 12, 6, and 8 appear in every line, so the columns stay aligned. The .2 in the last placeholder sets two decimal places. Precision gets its own chapter, so treat it as a given for now.
Repeating the numbers works for a tiny program. If you change a column width, you must change it in every line. A later chapter shows how to pass the width in as a variable so it appears once.
Gotchas
- Your own types ignore width by default. If you implement
Displaywith a plainwrite!, a spec like{:>10}has no effect, becausewrite!does not look at the padding options. The chapter onFormatter::padshows the fix. - Derived
Debugapplies the width to inner values, not to the whole output. Padding is passed down to each field, which usually gives odd results:
fn main() {
println!("[{:5?}]", Some(1));
}[Some( 1)]If you want the whole Option to occupy a column, convert it to a String first with format!("{:?}", value) and pad that string.
- A zero before the width changes the rules.
{:05}pads numbers with zeros and takes priority over any fill and alignment. That flag is covered with sign and precision.
Summary of rules
- Width is a minimum and counts
charvalues. - Strings,
char, andbooldefault to left alignment. Numbers default to right alignment. - Fill comes first and requires an alignment character right after it.
- Centering puts any odd leftover padding on the right.
- Types whose
Displayuses the padding options respect all of this. Custom types must opt in.
Exercise
Write one println! call that prints the word Total left-aligned in a field of 10 characters, then the number 7.5 right-aligned in a field of 8 characters with one decimal place, each field wrapped in square brackets. What exact line does it print?
Show answer
println!("[{:<10}][{:>8.1}]", "Total", 7.5); prints [Total ][ 7.5]. "Total" is 5 characters followed by 5 spaces, and "7.5" is 3 characters preceded by 5 spaces.
Exercise
What does println!("[{:^7}]", "abc") print, and why is it not symmetric?
Show answer
It prints [ abc ]. Wait: 7 minus 3 leaves 4 padding characters, which splits evenly as 2 and 2, so this one is symmetric. The odd case is an odd amount of padding, such as "ab" in width 7, which prints [ ab ] with the extra space on the right.