You do not have to invent a trait for every behavior. The standard library already defines the ones most functions need, and the built-in types implement them. Display means a value can be formatted with {} for a reader. PartialEq means two values can be compared with ==. Debug, which you have derived since Day 1, means a value can be formatted with {:?} for a programmer. Using these traits as bounds lets one function accept numbers, text and your own types alike.
Combine requirements with +: T: Display + PartialEq asks for both. Because both parameters below are written as T, the caller must pass two values of the same type. There is also a shorter form for a single argument: value: impl Display asks for some type implementing Display, without giving the type a name.
Predict and run
Which comparison changes the message? Which traits allow the comparison and the message?
use std::fmt::Display;
fn report<T: Display + PartialEq>(before: T, after: T) {
if before == after {
println!("Unchanged: {after}");
} else {
println!("Changed: {before} -> {after}");
}
}
fn main() {
report(12, 15);
report("Rust", "Rust");
}Check your prediction
Changed: 12 -> 15
Unchanged: RustPartialEq makes before == after legal, and Display makes {before} legal. Remove + PartialEq from the bound and predict the error: the comparison is now an operation the function never asked for, and the compiler rejects it with E0369, binary operation == cannot be applied to type T.
Same type, or any types
The single name T is a requirement in its own right. Calling report(12, "12") fails with error[E0308]: mismatched types, "expected integer, found &str". Each argument could be displayed on its own, but the first one fixed T as an integer, and the second must match. That is the behavior you want here, since comparing a number with text makes no sense.
When the arguments are unrelated, give each its own type. impl Display on each parameter does exactly that:
use std::fmt::Display;
fn line(label: impl Display, value: impl Display) {
println!("{label}: {value}");
}
fn main() {
line("Pages", 320);
line(7, String::from("Rust Patterns"));
line('#', 2.5);
}Pages: 320
7: Rust Patterns
#: 2.5Each impl Display is a separate, hidden type parameter, so any combination works. The rule of thumb: use impl Trait for independent arguments, and a named T when two arguments, or an argument and the result, must share a type.
Display for your own types
A struct has no Display until you write one, because Rust cannot guess how it should look to a reader. Implementing the trait takes one method, fmt, which writes the text with write!. After that, your type works with {}, with to_string(), and with any function bounded by Display.
use std::fmt;
#[derive(PartialEq)]
struct Book {
id: u32,
title: String,
}
impl fmt::Display for Book {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{} {}", self.id, self.title)
}
}
fn report<T: fmt::Display + PartialEq>(before: T, after: T) {
if before == after {
println!("Unchanged: {after}");
} else {
println!("Changed: {before} -> {after}");
}
}
fn main() {
let draft = Book { id: 7, title: String::from("Rust") };
let final_version = Book { id: 7, title: String::from("Rust Patterns") };
println!("{draft}");
let text: String = final_version.to_string();
println!("{text} has {} characters", text.len());
report(draft, final_version);
}#7 Rust
#7 Rust Patterns has 16 characters
Changed: #7 Rust -> #7 Rust Patterns#[derive(PartialEq)] compares field by field, so the two books differ because their titles differ. write! works like println! but writes into the formatter f, and returns a fmt::Result that fmt passes back. to_string() comes for free with every Display type.
Derive Debug, write Display
Debug output is for you and your tests, so derive it. Display output is for users, and only you know what they should see, so it is never derived.
Practice
Your turn
Write announce(item: impl Display) that prints Next: followed by the item. Call it with 7, an owned String::from("Rust") and the literal "Traits". Expected output: Next: 7, Next: Rust, Next: Traits. Then try announce(vec![1, 2]) and read why it is rejected.
use std::fmt::Display;
fn main() {
// Announce 7, an owned "Rust" string and "Traits".
}Hint 1: the idea
Only one argument needs a bound, so the function does not need to name a shared type.
Hint 2: a first step
Write fn announce(item: impl Display) and use {item} inside println!.
Worked solution
use std::fmt::Display;
fn announce(item: impl Display) {
println!("Next: {item}");
}
fn main() {
announce(7);
announce(String::from("Rust"));
announce("Traits");
}Next: 7
Next: Rust
Next: TraitsAll three types implement Display, and the call with the String moves it into the function, which is fine because nothing uses it afterward. The vector is rejected with error[E0277]: Vec<{integer}> doesn't implement std::fmt::Display: a list has no single obvious reader format, so it offers only Debug. Print it with {:?} instead. The checkpoint combines a generic struct with a trait bound.
Completion is saved in this browser only. It does not measure mastery.