Display, Debug, Clone, PartialEq
Some requirements in job postings are clear to any employer: "category B driver's license", "English at B2". Nobody spells them out in every posting: everyone knows what stands behind them.
In Rust, such shared requirements are the standard traits. The standard library declares them, and the language itself relies on them:
{:?}requires the traitDebug;.clone()requiresClone;==and!=requirePartialEq;{}requiresDisplay.
Numbers and strings have these traits already; vectors have all but Display, so a vector is printed with {:?}. Your struct does not have them until you give them to it. The compiler can write the first three for you.
Deriving traits with derive
You have already put the attribute #[derive(Debug)] on a struct to print it with {:?}. You can list several traits in the parentheses at once:
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let mut q = p.clone();
println!("{}", p == q); // true
q.y = 5;
println!("{}", p == q); // false
println!("{:?}", q); // Point { x: 1, y: 5 }
}Let's go through the example line by line:
#[derive(Debug, Clone, PartialEq)]asks the compiler to write three implementations forPoint.p.clone()creates a new point with copies of the fields, andpstays where it is.p == qcompares the points field by field and printstrue.q.y = 5changes only the copy:p == qis nowfalse.{:?}printsPoint { x: 1, y: 5 }.
Each derived trait does its work field by field. So derive works only if every field has the trait in question.
Debug
Debug printing with {:?}: the type's name and all its fields, almost as in a literal. The programmer sees it, not the program's user.
Clone
The .clone() method returns an independent copy of the value. For a String inside the struct, that is a new string on the heap, so clone can be expensive.
PartialEq
The operators == and !=. A derived PartialEq counts two values as equal when all their fields are equal. Without it, p == q on a struct does not compile.
Display is written by hand
{} is printing for a human, and it cannot be derived. The compiler does not know how your type should look to a user: a temperature could be written 21 °C, 21 degrees or +21. So you implement Display yourself:
use std::fmt;
struct Celsius(i32);
impl fmt::Display for Celsius {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} °C", self.0)
}
}
fn main() {
let t = Celsius(21);
println!("{}", t); // 21 °C
println!("{t}"); // 21 °C
}Let's go through it line by line:
use std::fmt;gives the short namesfmt::Display,fmt::Formatterandfmt::Result.impl fmt::Display for Celsiusis an ordinary trait implementation.Displayhas one required method,fmt.f: &mut fmt::Formatteris where the text gets written.println!creates it and passes it tofmt.write!(f, "{} °C", self.0)works likeprintln!, except that it writes intof. It returns afmt::Result, and that value becomes the result offmt.- Now
{}and{t}print21 °C.
Here the driver's license picture is off. A license is earned in an exam, while the compiler hands most standard traits to your type for one line of derive. The exception is Display: you always write it yourself.
Interviewers ask this: "Why can't Display be derived?" Debug printing has one honest format: all the fields. Printing for a human has no single right format, and the type's author chooses it.
Common mistake
The struct has #[derive(Debug)] and is printed with {}:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
println!("{}", p); // ✗
}error[E0277]: `Point` doesn't implement `std::fmt::Display`The program does not compile, so the first line prints nothing either. {} requires Display and never falls back to Debug. Even a tuple struct with one field, such as Meters(5), does not print as its value 5: it is a separate type, and it has no Display. The compiler suggests two fixes: print with {:?}, or implement Display.
Key points
{:?}requiresDebug,.clone()requiresClone,==requiresPartialEq,{}requiresDisplay.Debug,CloneandPartialEqare derived with#[derive(…)]if every field has them.Displayis never derived: you write it by hand, withimpl fmt::Displayandwrite!.- Without
Display, a line with{}is build error E0277, even whenDebugis there.