Rust for a C programmer · Lesson 03
Format text and numbers
Print a readable report, then build a formatted String that your caller can keep.
About 10 minutes of reading, then 20 minutes of practice.
Before reading: recall your borrowed return
Your unquote(&report) helper returned an &str.
Did that view own the text? What had to stay alive while you used it?
Answer from memory, then compare with
the earlier explanation.
Put expressions after the format string
A format string combines literal text with placeholders for values.
Each {} takes the next positional argument after the string:
let name = "probe";
println!("{}: {} bytes", name, name.len());
This prints probe: 5 bytes. You can also capture a variable by name,
or name an argument supplied to the macro:
println!("{name}: {} bytes", name.len());
println!("{name}: {len} bytes", len = name.len());
Both print the same line. Here len = names a formatting argument;
it does not declare a local variable. A placeholder can name a variable, but
{name.len()} is invalid: the method call belongs after the format string.
The Rust Book: printing variables and expressions.
Use numbered positions to reorder or repeat arguments. Counting starts at zero:
println!("{1}, then {0}, then {1}", "read", "open");
// open, then read, then open
Like a C printf call, the template determines how values appear.
Rust's formatting macros check the literal template and the arguments' types during compilation.
Plain {} works for both a string and an integer; you don't supply %s
or %u to identify their types.
Rust By Example: formatted print.
Set width, alignment, and precision
The colon inside a placeholder starts its formatting options. These examples use an ASCII sensor name so one character occupies one column:
let sensor = "probe";
let count = 7;
let reading = 3.5;
println!("|{sensor:<10}|{count:>6}|");
println!("reading={reading:.2}, count={count:04}");
Output:
|probe | 7|
reading=3.50, count=0007
| Options | Meaning in this example |
|---|---|
:<10 | Left-align the name in a field at least 10 characters wide. |
:>6 | Right-align the count in a field at least 6 characters wide. |
:.2 | Show the floating-point reading with two digits after the decimal point. |
:04 | Pad the integer with leading zeroes to at least four characters. |
Width is a minimum: a longer value expands the field. It does not get truncated. Precision controls how the floating-point value is displayed; it does not change the stored value. Worked formatting examples · Optional lookup: precision.
Choose where the text goes
| Macro | Result |
|---|---|
println!(…) | Write to standard output and append a newline. |
eprintln!(…) | Write to standard error and append a newline. |
format!(…) | Return an owned String containing the formatted text, with no added newline. |
All three use the same placeholder syntax. Rust By Example: output macros.
This helper borrows its input and creates a separate owned result:
fn greeting(name: &str) -> String {
format!("Hello, {name}!")
}
fn main() {
let name = String::from("Ada");
let message = greeting(&name);
println!("original: {name}");
drop(name);
println!("{message}");
}
The final expression in greeting has no semicolon, so its String becomes the
return value. Ownership passes to message; the result remains usable after
name is dropped. The input borrow is needed only during this call.
The Rust Book: return expressions ·
Building Strings with format!.
Formatting an existing String variable, as in println!("{name}"), borrows it.
An expression supplied as an argument can still perform a move of its own. Track what that
expression does, just as you would anywhere else.
The Rust Book: printing and ownership.
Optional: make Cargo reject a format string
Inside a working main, try each invalid line separately and run
cargo check. Remove it again before continuing.
let name = "probe";
println!("{name.len()}"); // Invalid: method call inside a placeholder.
println!("{} {}", name); // Invalid: the second placeholder has no argument.
Read the diagnostic's marked location and explanation. Both mistakes are caught before the program runs. See the reference for another type-checking example.
Exercise 1: print an aligned report
Create a fresh Cargo package and replace its generated program with your own implementation:
cd "/home/dmedeiros/Documents/ChatGPT/Teach Me Rust"
cargo new --bin --vcs none exercises/aligned-report
Write a helper called print_row that borrows a filename and receives a byte count
of type usize. Choose the function signature yourself.
It prints one row with a filename field at least 12 characters wide, left-aligned,
and a count field at least 6 characters wide, right-aligned. Use spaces for padding.
Put | around and between the fields, with one literal space on each side of each field.
In main, create an owned String containing notes.md.
Call your helper for the four cases below, then print that original String again.
Use formatting options to pad the fields; all filenames in this exercise are ASCII.
You can write four calls directly, without a loop.
| Filename | Byte count to pass |
|---|---|
notes.md | 8 |
README | 6 |
| Empty string | 0 |
archive.tar.gz | 1234567 |
Expected standard output, including spaces:
| notes.md | 8 |
| README | 6 |
| | 0 |
| archive.tar.gz | 1234567 |
still owned: notes.md
The last row deliberately exceeds both minimum widths. The byte counts are supplied data; they describe file sizes, not the lengths of the filenames.
cargo check --manifest-path exercises/aligned-report/Cargo.toml
cargo run --manifest-path exercises/aligned-report/Cargo.toml
For review: explain why the final print of the original String still works, and why the last row's separators don't line up with the rows above it.
Exercise 2: return a formatted label
cd "/home/dmedeiros/Documents/ChatGPT/Teach Me Rust"
cargo new --bin --vcs none exercises/formatted-label
Write a helper named make_label that borrows text and takes a job ID of type
u32. It returns an owned String and does no printing. Choose the signature and
use format! to produce the result.
The label contains the job ID padded with leading zeroes to a minimum width of four, the supplied text, and the text's UTF-8 byte length. Keep the spelling and punctuation shown below, with no newline in the returned String. Text may be empty or contain Unicode.
| Text and job ID | Exact returned contents |
|---|---|
notes.md, 7 | job 0007: notes.md (8 bytes) |
café, 42 | job 0042: café (5 bytes) |
Empty string, 0 | job 0000: (0 bytes) |
README, 12345 | job 12345: README (6 bytes) |
There are two spaces between the colon and opening parenthesis in the empty-text result.
The words in this table are actual text contents: "notes.md" is the Rust literal
you would write for the first input.
In main, create a String for the first input, store the returned label, and print
both the label and the original text. Check the other three cases too. Then make a separate
experiment: drop the original String before printing its stored label, and predict whether
that version compiles.
cargo check --manifest-path exercises/formatted-label/Cargo.toml
cargo run --manifest-path exercises/formatted-label/Cargo.toml
For review: who owns the returned text? Why can this result outlive the input String,
while the view from your earlier unquote exercise could not?