Modeling Data · 12 min · free lesson

Derive Macros

derive writes the obvious implementation so you do not have to.

Core idea

derive only compiles when every field also implements the trait.

Start with the idea

#[derive(Debug, Clone, PartialEq)] generates the mechanical implementation for each field. It only works when every field also implements the trait, which turns a missing capability deep in a struct into a clear compile error naming the field.

Read the code

#[derive(Debug, Clone, PartialEq, Default)]
struct Config {
    host: String,
    port: u16,
}

let a = Config::default();
let b = a.clone();
println!("{a:?} equal={}", a == b);

Four traits, no hand-written code, all checked by the compiler.

Practice starter

struct NoDebug;

#[derive(Debug)]
struct Wrapper {
    inner: NoDebug,
}

Practise this code in Playground ↗

Diagram for Derive Macros: a Rust code example flows to the lesson rule and the key observation.
Four traits, no hand-written code, all checked by the compiler.

Work through it

A trait describes a capability. Debug supports development formatting with {:?}; Clone makes an explicit copy; PartialEq enables equality comparisons; Default provides a conventional initial value. #[derive(...)] asks the compiler to generate straightforward implementations for a struct or enum. The generated code follows the fields: if a field cannot be cloned or printed, the containing type cannot derive that capability automatically.

Derive only the traits a type needs. Cloning a large structure can be expensive and may hide a design that should borrow instead. A default value is useful when it is meaningful, but Config::default() is a poor substitute for required settings that must be supplied by the caller. For an enum, deriving Default needs one designated default variant. Generated PartialEq compares corresponding fields, which might be wrong for a domain concept whose identity is based only on an ID. In that case, write the behavior deliberately rather than assuming the mechanical result is right.

Try the sample with println!("{a:?}"), a == b, and a.clone(). Then add a field whose type lacks Debug and inspect the compiler error; derive or implement Debug for that field if printing it is appropriate. This shows how trait bounds propagate through a model. Treat a derive list as part of the public promises of a type, and keep those promises intentional.

A derived Debug formatter can reveal sensitive fields. Before printing a configuration or token-bearing struct in diagnostics, decide whether to implement a redacted formatter instead. Compiler-generated convenience still deserves a review of what it exposes.

A derive asks the compiler to generate an implementation of a trait for a type. #[derive(Debug)] enables debug formatting, and common derives such as Clone, Copy, PartialEq, and Eq carry different contracts. Deriving is possible only when the type's fields support the requested trait. It does not make every operation free: cloning an owned String allocates, while copying a small integer is cheap.

For the example type, predict whether two values can be compared, printed with {:?}, or copied after assignment. Add one derive at a time and inspect any error about an unsupported field. Then add Copy to the derive list and see why the String in host rules it out. Do not derive traits merely to silence an error. Ask what callers should be allowed to do and what cost or semantics that operation has. A generated implementation is still part of your public type's behavior.

Try it

Derive the traits a small struct needs to be printed and compared.

What success looks like: The struct prints with {:?} and compares with == without manual code.

Check your understanding

Why can that struct not be printed?

Reveal the answer
  1. A struct cannot derive Debug when it has fields
  2. NoDebug does not implement Debug, so the field cannot be printed
  3. Debug always has to be written by hand for structs

A derived impl is only as available as the traits of its fields.

One more experiment

Add retries: u8 to Config and write the exact line you expect. Then declare struct NoDebug;, add a field of that type, and predict which of the four derives rustc rejects.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Derive Macros (courseId "basics", lessonId "derive")
Link: https://crabrix.com/learn/basics/derive/
Goal: derive only compiles when every field also implements the trait.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/derive) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.