Sub topic 2
Getting implementations for free with derive
This chapter assumes you know basic structs and enums, what impl Trait for Type means, and how println! format strings work.
What derive does
Writing impl Debug for Point by hand is repetitive when the body only lists fields. The #[derive(...)] attribute asks the compiler to generate that impl for you at compile time.
#[derive(Debug, Clone, PartialEq, Default)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = a.clone();
println!("{}", a == b);
println!("{:?}", Point::default());
}This prints true and then Point { x: 0, y: 0 }. Four lines of attribute replaced four hand-written impl blocks.
The field rule
A derived implementation works by calling the same trait on each field. So derive only compiles when every field already implements the trait.
#[derive(Debug)]
struct Token;
#[derive(Debug)]
struct Wrapper {
token: Token,
}
fn main() {
println!("{:?}", Wrapper { token: Token });
}This prints Wrapper { token: Token }. If you remove #[derive(Debug)] from Token, the compiler reports that Token doesn't implement Debug. The error points at the field, not at the derive line. The fix is to derive on the field's type, or to implement the trait by hand on the outer type.
Generic types follow the same rule. For struct Pair<T>, #[derive(Debug)] generates impl<T: Debug> Debug for Pair<T>. The bound is added to every type parameter, even if a parameter appears only in a way that does not need it.
What you can and cannot derive
Only some traits have derive support. The traits from this tutorial split like this:
| Trait | Derivable? | Notes |
|---|---|---|
| `Debug` | Yes | Output shape is fixed by the compiler. |
| `Default` | Yes | Every field must implement `Default`. Enums need `#[default]` on one variant. |
| `Display` | No | There is no single obvious user-facing text, so you write it. |
| `From` | No | The compiler cannot guess which source type you mean. |
Deriving versus writing by hand
Derive when the generated behavior is what you want. Write the impl by hand when it is not. A common reason is a Debug impl that must not print a secret field. Another is a Default that should be something other than zeros and empty strings. Later chapters cover both cases.
Derived and hand-written implementations are interchangeable to callers. You can switch from one to the other without changing any code that uses the type.
Exercise
You write #[derive(Debug)] struct Job { id: u32, handler: Handler }, but Handler has no Debug implementation. What happens, and what are two ways to fix it?
Show answer
Compilation fails because derived Debug requires every field type to implement Debug. Fix it by adding #[derive(Debug)] to Handler, or by implementing Debug for Job by hand (for example with debug_struct) and leaving out or replacing the handler field.