Skip to content
Theory · Generics and traits · lesson 6 of 8

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 trait Debug;
  • .clone() requires Clone;
  • == and != require PartialEq;
  • {} requires Display.

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:

Rust
#[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:

  1. #[derive(Debug, Clone, PartialEq)] asks the compiler to write three implementations for Point.
  2. p.clone() creates a new point with copies of the fields, and p stays where it is.
  3. p == q compares the points field by field and prints true.
  4. q.y = 5 changes only the copy: p == q is now false.
  5. {:?} prints Point { 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:

Rust
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:

  1. use std::fmt; gives the short names fmt::Display, fmt::Formatter and fmt::Result.
  2. impl fmt::Display for Celsius is an ordinary trait implementation. Display has one required method, fmt.
  3. f: &mut fmt::Formatter is where the text gets written. println! creates it and passes it to fmt.
  4. write!(f, "{} °C", self.0) works like println!, except that it writes into f. It returns a fmt::Result, and that value becomes the result of fmt.
  5. Now {} and {t} print 21 °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 {}:

Rust
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{:?}", p);
    println!("{}", p); // ✗
}
TEXT
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

  • {:?} requires Debug, .clone() requires Clone, == requires PartialEq, {} requires Display.
  • Debug, Clone and PartialEq are derived with #[derive(…)] if every field has them.
  • Display is never derived: you write it by hand, with impl fmt::Display and write!.
  • Without Display, a line with {} is build error E0277, even when Debug is there.