Sub topic 5
Display: output meant for users
This chapter assumes you can write and run a basic Rust program and know what a trait is. You should also know the {} placeholder from the previous chapters.
What Display is
Display is a trait in std::fmt. A type that implements it can be printed with the plain {} placeholder. The trait has one job: produce text meant for the people who use your program, such as messages, reports, and prompts.
Rust's primitive types and String already implement it.
fn main() {
let n = 42;
let pi = 3.5;
let ok = true;
let c = 'x';
let s = "hello";
println!("{n} {pi} {ok} {c} {s}");
}This prints 42 3.5 true x hello.
Why some types have no Display
Many types do not implement Display. Vec<i32>, Option<i32>, tuples, and your own structs are examples. Writing println!("{}", vec![1, 2, 3]) fails to compile with the error `Vec<i32> doesn't implement std::fmt::Display``.
This is deliberate. A user-facing form of a list has no single right answer. It could be 1, 2, 3, [1, 2, 3], or one item per line. The standard library does not guess, so you choose the format yourself. If you only need to look at the value while developing, use {:?}, which the next chapter covers.
Display is not Debug
The two traits are separate because they serve different readers. Display output is designed and stable. Debug output is mechanical and meant for programmers. The same value can print differently under each:
fn main() {
println!("{} {:?}", 3.0, 3.0);
println!("{} {:?}", "hi", "hi");
println!("{} {:?}", 'a', 'a');
}This prints:
3 3.0
hi "hi"
a 'a'Debug keeps quotes and the decimal point so you can tell the type of a value. Display leaves them out because a user does not need them.
Display gives you to_string
Any type that implements Display also gets a to_string() method. The standard library provides it through a blanket implementation of the ToString trait. You can also use Display as a bound to accept any printable value:
use std::fmt::Display;
fn announce<T: Display>(value: T) -> String {
format!("Result: {value}")
}
fn main() {
println!("{}", announce(7));
println!("{}", announce("done"));
let s = 2.5_f64.to_string();
println!("{s} has {} characters", s.len());
}This prints Result: 7, Result: done, and 2.5 has 3 characters.
Common errors
- Using
{}on a collection,Option, or a struct. Switch to{:?}for inspection. For user output, build the text yourself, for example withjoin, or implementDisplayfor your own type. - Passing a type that lacks
Displayto a function bounded byT: Display. The compiler reports the missing trait at the call site. - Expecting
{}and{:?}to match for floats and strings. They differ, as shown above.
Exercise
Why does println!("{}", vec![1, 2, 3]); fail to compile, and what are two ways to get output instead?
Show answer
Vec<i32> does not implement Display, because there is no single obvious user-facing text for a list. For a quick look at the value, use println!("{:?}", vec![1, 2, 3]);, which prints [1, 2, 3]. For user-facing output, build the text yourself. One way is to convert each item to a string and join them, for example v.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(", ").