Sub topic 2
Getting implementations for free with derive
This chapter assumes you know what a trait is and how impl Trait for Type works. It also assumes you can read basic struct and enum definitions. By the end you will know what #[derive(...)] generates, what it requires of your types, and when to write the implementation yourself.
What derive does
Many standard traits have an obvious implementation that follows the shape of the type. Debug prints the type name and each field. Clone clones each field. PartialEq compares each field. Writing these by hand is repetitive and easy to get wrong when you add a field later.
The derive attribute asks the compiler to write the impl block for you. You place it directly above a struct or enum:
#[derive(Debug, Clone, PartialEq)]
struct Reading {
label: String,
value: f64,
}Derive is a procedural macro. It runs at compile time, reads the definition of your type, and emits ordinary Rust code. The result is the same as an impl you typed yourself, with no runtime cost.
The rule: every field must support the trait
A derived implementation works by calling the same trait on each field. So #[derive(Debug)] only compiles if every field type also implements Debug. The same holds for enum variants and their payloads.
#[derive(Debug)]
struct Opaque(u32);
#[derive(Debug)]
struct Wrapper {
name: String,
inner: Opaque,
}
fn main() {
let w = Wrapper {
name: "w".to_string(),
inner: Opaque(7),
};
println!("{:?}", w);
}This prints Wrapper { name: "w", inner: Opaque(7) }. If you removed #[derive(Debug)] from Opaque, the compiler would reject the derive on Wrapper and point at the inner field. The fix is to derive or implement the trait on the field's type. If the field type comes from another crate and has no Debug, you can't add one (Rust's orphan rule forbids that), so you write the trait for the outer type by hand and skip that field.
Which traits can be derived
The standard library supports derive for a fixed list of traits. Display and From are not on it, because no single obvious implementation exists for them.
| Trait | What the derive does | Extra requirement |
|---|---|---|
| `Debug` | Prints type name and fields | All fields `Debug` |
| `Clone` | Clones each field | All fields `Clone` |
| `Copy` | Marks the type as bitwise-copyable | Must also derive `Clone`; all fields `Copy` |
| `PartialEq` | Equal when all fields are equal | All fields `PartialEq` |
| `Eq` | Declares equality is total | Must also have `PartialEq`; no `f32`/`f64` fields |
| `PartialOrd` | Compares in declaration order | Must also have `PartialEq` |
| `Ord` | Total ordering in declaration order | Must also have `Eq` and `PartialOrd` |
| `Hash` | Hashes each field | All fields `Hash` |
| `Default` | Uses `Default::default()` for each field | All fields `Default`; enums need `#[default]` |
The tutorial's four main traits split cleanly. Debug and Default can be derived. Display can never be derived, so you always write it. From is also always written by hand.
Several derives at once
You list traits in one attribute, separated by commas. Order does not matter, but a trait that depends on another needs that one present too.
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Level {
Low,
Medium,
High,
}
#[derive(Debug, Clone, PartialEq, Default)]
struct Reading {
label: String,
value: f64,
}
fn main() {
println!("{}", Level::Low < Level::High);
let mut seen = HashSet::new();
seen.insert(Level::Low);
seen.insert(Level::Low);
println!("{}", seen.len());
let r = Reading {
label: "temp".to_string(),
value: 1.5,
};
let r2 = r.clone();
println!("{}", r == r2);
println!("{:?}", Reading::default());
}The output is true, 1, true, and Reading { label: "", value: 0.0 }.
Two details are worth noticing. Reading derives PartialEq but not Eq, because f64 has NaN, which is not equal to itself. And Level can be a HashSet member because it derives Hash and Eq.
Derived ordering follows the source. For a struct, fields are compared in the order you declared them. For an enum, variants are compared by their position, so Low < Medium < High here. If you reorder the variants, you change the behavior of <.
What the derive expands to
A derive is not magic. For a generic type, it adds a bound on each type parameter. This definition:
#[derive(Debug)]
struct Pair<T> {
first: T,
second: T,
}produces roughly the code below, which you can write yourself and run:
use std::fmt;
struct Pair<T> {
first: T,
second: T,
}
impl<T: fmt::Debug> fmt::Debug for Pair<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pair")
.field("first", &self.first)
.field("second", &self.second)
.finish()
}
}
fn main() {
let p = Pair { first: 1, second: 2 };
println!("{:?}", p);
}This prints Pair { first: 1, second: 2 }. The T: fmt::Debug bound is the part to remember. Pair<Opaque> is Debug only when Opaque is Debug. The bound is placed on T even if no field actually needs it, such as a PhantomData<T> field. This is a known limit of the derive macro. If it blocks you, write the impl by hand with a looser bound.
Edge cases and gotchas
- Derive writes the impl for the whole type. You can't derive a trait for only some fields. To leave one out, write the impl yourself, as the
Credentialsexample later in this tutorial does to hide a password. - Derive is public output.
#[derive(Debug)]prints every field, including secrets such as tokens. Logging a derivedDebugvalue can leak them. Copyis a promise about semantics. It needsCloneas well, and it changes how assignment works: values are copied, not moved. Derive it only for small plain-data types.PartialOrdandEqinteract with floats. A struct with anf64field can derivePartialEqandPartialOrd. It can't deriveEqorOrd.Defaulton enums needs a marked variant. Mark one unit variant with#[default], or the derive fails. A later chapter covers this.- Derive adds to the type's public API. If you publish a library,
#[derive(Clone)]is a promise to your users. Removing it later is a breaking change.
Deciding between derive and a manual impl
Derive when the obvious field-by-field behavior is what you want. This covers most Debug, Clone, PartialEq, and Hash implementations, and it stays correct as fields are added. Write the impl by hand when:
- The output or behavior must differ from the field-by-field default, for example masking a field or comparing only an
id. - A field type can't support the trait, and you want to skip it.
- A generic type needs looser bounds than the derive would add.
- The trait has no derive at all, as with
DisplayandFrom.
Exercise
A struct Config has fields name: String and timeout: f64. You write #[derive(Debug, Clone, PartialEq, Eq)] above it and the code does not compile. Why does it fail, and what is the smallest change that makes it compile?
Show answer
Eq can't be derived because f64 does not implement Eq. A NaN value is not equal to itself, so equality is not total. Remove Eq from the derive list. PartialEq still works, and Debug and Clone are unaffected. The alternative is to change timeout to an integer type, such as milliseconds in a u64, which does implement Eq.
Exercise
You define struct Session { user: String, token: String } and derive Debug. A teammate adds println!("{:?}", session) to a log statement. What is the risk, and how do you remove it without losing Debug output for user?
Show answer
The derived output includes token, so the secret goes into the logs. Remove the derive and implement fmt::Debug by hand using f.debug_struct("Session"). Add .field("user", &self.user) and .field("token", &"<hidden>"), then call .finish(). The output keeps the usual shape but never shows the token.