Sub topic 10
Deriving Debug, Clone, PartialEq, and Default
This chapter assumes you can define a struct, create instances, and read the basics of ownership (moves and borrows). Writing trait implementations by hand is tedious, so Rust can generate them for you.
What `derive` does
The #[derive(...)] attribute goes above a struct. At compile time it generates a standard impl block for each trait you list. The generated code applies the trait to every field in turn.
| Trait | What it gives you | Generated behavior |
|---|---|---|
| `Debug` | `{:?}` and `{:#?}` formatting | Prints the struct name and each field |
| `Clone` | `.clone()` | Clones every field |
| `PartialEq` | `==` and `!=` | Equal if every field is equal |
| `Default` | `Type::default()` | Uses each field type's default |
All four together
#[derive(Debug, Clone, PartialEq, Default)]
struct Settings {
name: String,
retries: u32,
verbose: bool,
}
fn main() {
let a = Settings::default();
let mut b = a.clone();
b.retries = 3;
println!("{:?}", a);
println!("{:#?}", b);
println!("equal: {}", a == b);
}This prints:
Settings { name: "", retries: 0, verbose: false }
Settings {
name: "",
retries: 3,
verbose: false,
}
equal: false{:?} prints on one line. {:#?} is the pretty form, which is easier to read for nested data.
Details that matter
- Debug output is for developers. Its format is not guaranteed to stay stable. Use
Displayfor user-facing text. - Clone is a deep copy of owned data. Cloning
Settingsallocates a newString. The clone is independent, so changingbnever affectsa. - PartialEq compares field by field. Two structs with identical field values are equal, even if they are different instances in memory.
- Default uses each field's own default. Numbers are
0,boolisfalse,Stringis empty, andOption<T>isNone. If you want other values, implementDefaultby hand or override fields with struct update syntax:Settings { retries: 5, ..Default::default() }.
Common errors
Derive only works when every field's type implements the trait. This fails to compile:
struct Token;
#[derive(Debug)]
struct Wrapper {
token: Token,
}The compiler reports that Token doesn't implement Debug. Add the derive to Token as well:
#[derive(Debug)]
struct Token;
#[derive(Debug)]
struct Wrapper {
token: Token,
}
fn main() {
println!("{:?}", Wrapper { token: Token });
}Two related gotchas:
- A struct with an
f64field can derivePartialEqbut notEq, becauseNaN != NaN. Types used asHashMapkeys needEq. - Deriving
Cloneon a struct that holds aVecorStringcan be expensive. Borrow with&when you don't need your own copy.
Exercise
A struct Job has fields id: u32 and payload: Vec<u8>. You derive Debug, Clone, PartialEq, Default on it. What does Job::default() contain, and what happens if you add a field of a type Socket that implements none of these traits?
Show answer
Job::default() has id equal to 0 and payload equal to an empty vector. Adding the Socket field makes the derives fail to compile, because each derived trait requires every field type to implement that trait. The fix is to derive or implement the traits on Socket, or to implement the traits for Job by hand.