Sub topic 5
Display: output meant for users
This chapter covers what the {} placeholder asks of a type, which standard types satisfy it, and the errors you get when a type doesn't. It assumes you can write a basic Rust program, know what a struct is, and have seen println! with {}. It also assumes you know a trait is a named set of methods a type can implement. You won't write your own Display implementation here. That comes in a later chapter.
What `{}` asks for
Every placeholder in a format string names a formatting trait. An empty {} means std::fmt::Display. Display is the trait for text meant for the end user: a message, a report line, or a value in a form a person would write.
The trait has one required method, fmt. It receives the value and a Formatter, which is the destination plus the options from the placeholder. When println! reaches a {}, it calls Display::fmt for that argument and writes the result into the output.
Which types have Display
The standard library implements Display for types that have an obvious human-readable form:
- Integers and floats.
boolandchar.strandString.- References to any type that implements Display.
- Many error types, such as
ParseIntError.
fn main() {
println!("{}", "text");
println!("{}", 42);
println!("{}", 2.50);
println!("{}", 'x');
println!("{}", true);
println!("{}", String::from("owned"));
println!("{}", 1.0);
println!("{}", 0.1 + 0.2);
}The output is text, 42, 2.5, x, true, owned, 1, and 0.30000000000000004. Two details are worth noting:
- Display prints the shortest text that identifies the float. It does not keep trailing zeros, so
2.50prints as2.5and1.0prints as1. - The
0.30000000000000004result is floating-point arithmetic, not a formatting bug. Use a precision such as{:.2}when you want fixed decimals.
Display for a string writes the characters as they are, with no quotes and no escapes. This is the main visible difference from Debug, which the next chapter covers.
Types that do not have Display
Several common types deliberately lack Display. These include Vec<T>, Option<T>, tuples, arrays, and (). Each has many reasonable text forms. A vector could be 1, 2, 3, [1, 2, 3], or one item per line. The standard library does not pick one for you.
Passing such a value to {}, for example println!("{}", vec![1, 2, 3]);, fails at compile time with an error like this:
error[E0277]: `Vec<{integer}>` doesn't implement `std::fmt::Display`
= help: the trait `std::fmt::Display` is not implemented for `Vec<{integer}>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) insteadThe note at the end is the compiler suggesting Debug. That is often right while you are debugging. If you want user-facing output, build the text yourself:
fn main() {
let nums = vec![1, 2, 3];
let parts: Vec<String> = nums.iter().map(|n| n.to_string()).collect();
println!("{}", parts.join(", "));
}This prints 1, 2, 3. The same rule applies to your own structs and enums. They have no Display until you write it, and #[derive(Display)] does not exist. Display has no derive because the compiler cannot guess what your type should look like to a user.
Display and `to_string`
Any type that implements Display gets a to_string() method for free. The standard library has a blanket implementation of the ToString trait for every T: Display. It runs the same fmt code and collects the output into a String.
fn main() {
let n = 255;
let s = n.to_string();
println!("{} has {} characters", s, s.len());
}This prints 255 has 3 characters. Because to_string is built on Display, you should implement Display on your own types and never ToString directly.
Display as a bound
Because Display is a trait, you can require it in generic code. The bound T: Display says "I can print this for a user":
use std::fmt::Display;
fn announce<T: Display>(item: T) {
println!("Now showing: {item}");
}
fn main() {
announce("a string slice");
announce(7);
announce(3.5);
let owned = String::from("owned");
announce(&owned);
}All four calls compile. &String works because the standard library implements Display for any reference &T where T: Display. A call such as announce(vec![1, 2]) would be rejected at the call site with the same E0277 error, before the function body is compiled.
Format options on Display types
The built-in Display implementations respect the options you put after the colon. Width, fill, alignment, precision, and sign all work. Their meaning depends on the type:
| Placeholder | Value | Output | Effect |
|---|---|---|---|
| `{:>6}` | `42` | `[ 42]` | Right-align in 6 columns |
| `{:.1}` | `3.14159` | `3.1` | One digit after the decimal point |
| `{:.3}` | `"hello"` | `hel` | Truncate a string to 3 characters |
| `{:<6}` | `"ab"` | `ab ` | Left-align, pad with spaces |
The brackets in the table's output column show the field edges. The second row is a good reminder that precision does different jobs for different types. For floats it counts decimal places. For strings it sets a maximum length.
The next chapters cover these options in detail. The relevant point here is that a custom Display implementation does not get this behavior automatically. A type that only writes text ignores the caller's width. A later chapter shows how Formatter::pad fixes that.
Display on errors
Error types implement Display so that you can show them to a person. That is the intended use:
fn main() {
match "abc".parse::<i32>() {
Ok(n) => println!("number: {n}"),
Err(e) => println!("could not parse: {e}"),
}
}This prints could not parse: invalid digit found in string. Using {e} gives a sentence designed to be read. Using {e:?} would give the internal structure, ParseIntError { kind: InvalidDigit }, which is more useful to a programmer than to a user.
Why Display and Debug are separate traits
Rust keeps them apart for three reasons:
- User text needs a decision that only the author of the type can make. Debug text is mechanical, so it can be generated by
#[derive(Debug)]. - The two goals conflict. A string is shown as
hito a user and as"hi"to a programmer who needs to see its exact contents. - Having both lets one type serve both audiences. The compiler stops you from sending the wrong one by accident, because each placeholder asks for a specific trait.
Common mistakes
- Using
{}on aVec,Option, tuple, or your own struct and getting E0277. Either implement Display, convert the value to a string yourself, or use{:?}if the output is for debugging. - Expecting
1.0to print as1.0. Display prints1. Debug prints1.0. - Writing
impl ToString for MyType. Implement Display instead and let the blanket implementation supplyto_string. - Assuming width and alignment work on every Display type. They work on the built-in types, but a custom type must opt in.
Exercise
The line println!("{}", Some(5)); does not compile. Which trait is missing, which error code appears, and name one way to print the value anyway.
Show answer
Option<i32> does not implement Display, so the compiler reports E0277 (Option<{integer}> doesn't implement std::fmt::Display). You can print it with {:?}, which gives Some(5). For user-facing text, match on the option instead, for example if let Some(n) = x { println!("{n}") }.
Exercise
Write a generic function describe that takes any value that can be shown to a user and returns a String of the form value: <text>. Then give the output of describe(1.0).
Show answer
use std::fmt::Display;
fn describe<T: Display>(item: T) -> String {
format!("value: {item}")
}
describe(1.0) returns value: 1, because Display prints the float 1.0 without a trailing .0.