Sub topic 10
Deriving Debug, Clone, PartialEq, and Default
This chapter assumes you can define a struct and write an impl block. It also assumes you know how moves and borrows work. Here you will use #[derive(...)] to get four common traits without writing them by hand. You will also see when the generated code is wrong for your type.
What derive does
#[derive(Trait)] is an attribute placed above a struct. At compile time it generates an impl Trait for YourStruct block. The generated code applies the trait to each field in order. Derive saves typing, and it keeps the implementation in sync when you add or remove fields.
The central rule is that a derive works only if every field's type already implements that trait. A String field is fine for all four traits in this chapter. A field whose type does not implement the trait produces a compile error.
| Trait | What the generated code does | Typical use |
|---|---|---|
| `Debug` | Prints the type name and every field | `{:?}`, `{:#?}`, `dbg!`, `assert_eq!` messages |
| `Clone` | Calls `.clone()` on every field | Making an independent copy with `.clone()` |
| `PartialEq` | Compares every field with `==` | `==`, `!=`, `assert_eq!` |
| `Default` | Calls `Default::default()` on every field | `Type::default()`, struct update syntax |
All four on one struct
#[derive(Debug, Clone, PartialEq, Default)]
struct Settings {
name: String,
retries: u32,
verbose: bool,
timeout: Option<u32>,
}
fn main() {
let a = Settings::default();
let mut b = a.clone();
println!("{}", a == b);
b.retries = 3;
println!("{}", a == b);
println!("{:?}", a);
println!("{:#?}", b);
}This prints:
true
false
Settings { name: "", retries: 0, verbose: false, timeout: None }
Settings {
name: "",
retries: 3,
verbose: false,
timeout: None,
}You can list several traits in one attribute, in any order.
Debug
Debug output is meant for programmers, not end users. {:?} prints on one line. {:#?} prints a multi-line, indented form that is easier to read for nested data. The dbg! macro prints a value with its file and line number to standard error and returns the value, so you can wrap an expression without changing the program.
Two points matter in practice:
- Derived
Debugprints every field, including private ones and any secrets. If a struct holds a password or token, writeDebugby hand and skip that field. - The output format is not a stable interface. Do not parse it or compare it in tests. Compare values with
==instead.
Clone
Derived Clone calls clone on each field and builds a new struct from the results. The copy owns its own data, so changing one value does not affect the other.
#[derive(Debug, Clone)]
struct Playlist {
title: String,
tracks: Vec<String>,
}
fn main() {
let original = Playlist {
title: String::from("Morning"),
tracks: vec![String::from("A"), String::from("B")],
};
let mut copy = original.clone();
copy.tracks.push(String::from("C"));
println!("{:?}", original.tracks);
println!("{:?}", copy.tracks);
}The original keeps two tracks and the copy has three. String and Vec allocate on the heap, so each clone allocates new memory. Cloning a large struct in a loop can be a real cost. Where a borrow would do, prefer &Playlist to .clone().
What "clone" means depends on the field type. A shared reference &T is copied as a pointer, so the clone still points at the same data. An Rc<T> clone increments a reference count and does not copy the contents. Derived Clone follows each field's own Clone implementation.
Clone is not Copy. Copy is a separate marker trait that makes assignment copy the value implicitly instead of moving it. It can be derived only if every field is Copy, and String is not. Derive Clone first, and add Copy only for small plain-data types.
PartialEq
Derived PartialEq makes == true only when every field is equal. Fields are compared in declaration order, and comparison stops at the first difference. Both sides must be the same type.
#[derive(Debug, PartialEq)]
struct Reading {
sensor: String,
value: f64,
}
fn main() {
let a = Reading { sensor: String::from("t1"), value: 20.5 };
let b = Reading { sensor: String::from("t1"), value: 20.5 };
let nan1 = Reading { sensor: String::from("t2"), value: f64::NAN };
let nan2 = Reading { sensor: String::from("t2"), value: f64::NAN };
println!("{}", a == b);
println!("{}", nan1 == nan2);
}The first line prints true and the second prints false. In floating point, NaN is not equal to itself. Because of that, f64 implements PartialEq but not Eq, and a struct containing an f64 cannot derive Eq. That is the reason the trait is called PartialEq: equality is not guaranteed to hold for every value, even x == x. If your struct has only integer, string, and bool fields, you can also derive Eq. Types used as HashMap keys need Eq and Hash.
Derived equality compares all fields. If two values should count as equal when only some fields match, such as comparing users by id alone, write PartialEq by hand.
Default
Default provides a standard starting value through Type::default(). The derived version calls default() on each field. The values you get for common types are:
- Numbers are
0or0.0. boolisfalse.StringandVec<T>are empty.Option<T>isNone.
Combine Default with struct update syntax to set only the fields you care about:
#[derive(Debug, Default)]
struct Job {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let job = Job {
name: String::from("backup"),
retries: 3,
..Default::default()
};
println!("{:?}", job);
}The ..Default::default() expression must come last. It fills verbose from the default value.
When the derived default is wrong
Zero and empty values are not always valid. A port of 0 or an empty host name may break your program's rules. In that case, implement Default yourself:
#[derive(Debug)]
struct Connection {
host: String,
port: u16,
retries: u32,
}
impl Default for Connection {
fn default() -> Self {
Self {
host: String::from("localhost"),
port: 8080,
retries: 3,
}
}
}
fn main() {
let c = Connection {
port: 9000,
..Default::default()
};
println!("{:?}", c);
}Struct update syntax works the same way with a hand-written default. If you also need to guarantee that no instance can hold invalid values, make the fields private and expose a constructor. An exposed Default lets anyone build the default state.
Generic structs and derive bounds
Derive on a generic struct adds a trait bound on each type parameter. This code:
#[derive(Debug, Clone, PartialEq)]
struct Wrapper<T> {
value: T,
}generates impls equivalent to impl<T: Clone> Clone for Wrapper<T>. So Wrapper<i32> is Clone, but Wrapper<NoClone> is not, where NoClone is a type without Clone. The compiler reports this at the call to .clone(), not at the struct definition. The bound is added even when T appears only behind a pointer, which can be stricter than needed. In that rare case, write the impl by hand.
Common errors
- A field type lacks the trait. Deriving
Cloneon a struct that contains a type withoutClonefails to compile. Derive the trait on the inner type, or implement it by hand. - Deriving
Defaulton a struct that holds a type withoutDefault. The same rule applies. Wrapping the field inOption<T>is a common fix, sinceOption<T>has a default ofNonefor anyT. - Comparing different types with
==. DerivedPartialEqonly compares a type with itself. Compare the fields you want directly. - Expecting
Debugto hide private fields. It does not. Privacy limits access in code, and it does not affect formatting. - Cloning to silence the borrow checker. An extra
.clone()compiles, but it hides an ownership design problem and costs allocations.
Exercise
A struct Order has fields id: u32, total: f64, and note: Option<String>. You write #[derive(Debug, Clone, PartialEq, Eq, Default)] on it. Does it compile? If not, why, and what is the smallest fix? Also, what does Order::default().note contain?
Show answer
It does not compile, because Eq cannot be derived when a field is f64. f64 does not implement Eq since NaN != NaN. The smallest fix is to remove Eq from the derive list. PartialEq already gives you ==. Order::default().note is None, because Option<String> defaults to None.