Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
APPENDIX C / E · REFERENCE NOTES

Appendix C · Derivable traits.

Know what generated trait implementations promise and where a manual rule is needed.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

A derive attribute asks a procedural macro to generate an implementation for a named trait. Common standard-library derives include Debug for inspection, Clone for explicit duplication, Copy for inexpensive implicit copying when every field permits it, and PartialEq for equality comparisons. Deriving is convenient because the generated behavior follows the fields and variants consistently.

Generated behavior is not automatically the domain rule you want. Derived equality compares the stored fields according to their own equality rules; a business concept might instead compare stable identifiers. A derived Debug representation may expose internal or sensitive fields in logs. Choose a derive because its semantics fit the type, not because it removes a few lines of code.

02 / THE RULES

What Rust is checking.

A derive can fail when a field type does not implement the required trait. That failure is useful information: generated Clone cannot clone a resource that has no clone semantics, and Copy cannot be derived for a type that owns data needing destruction. Debug and Display are distinct: Debug is intended for developer-facing representation, while Display is a human-facing formatting contract implemented manually.

Derive macros from external crates can generate serialization or other implementations, but those crates and their attributes become part of the build and API story. Read generated behavior through the trait's contract and the type's fields. The examples below show a struct with Debug and ordinary enum-based behavior, so the difference between generated capability and deliberately written domain logic remains visible.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Structs & field ownership

A struct groups named fields into a new type. Ownership rules apply to each field: a String field is owned, while a reference field borrows and needs a lifetime relationship. Start with owned fields when a value should stand independently. Struct update syntax can move fields from the original, so do not assume the original remains fully usable. Deriving Debug gives an inspection format; a public-facing report can use a deliberate formatter instead.

structs.rs
#[derive(Debug)]
struct Task {
    title: String,
    complete: bool,
}
fn main() {
    let task = Task {
        title: String::from("Ship the build"),
        complete: false,
    };
    println!("{}: {}", task.title, task.complete);
}
OUTPUT
Ship the build: false
  1. Task is a new domain type, not an unlabelled tuple.
  2. Its title owns its String.
  3. Accessing fields for formatting borrows the data in this example.

The boundary: Making one field pub does not make every field public. Design the public API deliberately.

EXAMPLE 02

Copy, Clone & cost

Small scalar types such as i32 implement Copy: assigning them leaves both values usable. A String does not implement Copy because it owns a heap buffer. clone explicitly creates another owned String and copies the text. Clone has type-specific behavior: cloning an Arc increments a reference count rather than deeply copying its payload. Read the type and its API before assuming what duplication costs. Borrow when you only need temporary access; clone when independent ownership is actually part of the design.

copy-clone.rs
fn main() {
    let a = 7;
    let b = a;
    let first = String::from("Rust");
    let mut second = first.clone();
    second.push('!');
    println!("{a} {b}: {first} / {second}");
}
OUTPUT
7 7: Rust / Rust!
  1. The integer assignment copies.
  2. String::clone creates independently owned text.
  3. Changing second does not change first.

The boundary: Cloning to fix every borrowing error can hide an unclear ownership model and add unnecessary allocations.

EXAMPLE 03

Enums & data-bearing variants

An enum describes one of several variants, and each variant can carry a different data shape. This is useful for states such as queued, running with a worker ID, or failed with a message. A pair of booleans could express contradictory combinations; an enum can make those states unrepresentable. Pattern matching inspects the variant and binds its data. Derive traits only when their behavior fits the data, and prefer domain types to magic strings for closed sets of choices.

enums.rs
enum Job {
    Queued,
    Running { worker: u32 },
    Failed(String),
}
fn describe(job: Job) -> String {
    match job {
        Job::Queued => "queued".into(),
        Job::Running { worker } => format!("worker {worker}"),
        Job::Failed(reason) => format!("failed: {reason}"),
    }
}
fn main() {
    println!("{}", describe(Job::Running { worker: 7 }));
    assert_eq!(describe(Job::Queued), "queued");
    assert_eq!(describe(Job::Failed("offline".into())), "failed: offline");
}
OUTPUT
worker 7
  1. Running carries a named worker field.
  2. Failed owns its message.
  3. The match handles every variant.

The boundary: Do not hide a useful domain enum behind arbitrary strings if callers need exhaustive checks.

04 / THE CONNECTION

Keep this model.

Derive creates a standard implementation from a type's structure. It cannot decide whether that structure matches your domain's idea of equality, display, or duplication.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.