← Fundamentals
Fundamentals

Rust traits, impl blocks, and derive

What does derive write for you, and when must you write a trait yourself?

Derived traits build behavior from fields, so the field contracts shape the result.

Outcome

Predict what a derived Debug, Clone, PartialEq and Ord do, say when derive(Copy) is refused, recognize a derived Clone that shares through an Rc, and write an Ord that orders by the right key and still agrees with equality.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

derive
For the standard traits shown here, an attribute that generates an impl using the fields’ trait implementations. Other derive macros can define other rules.
Inherent impl
An impl Type block of methods that belong to the type itself, not to any trait.
Lexicographic order
Comparing the first field, then the next on a tie, and so on; what derived Ord does.
Coherent ordering
An Ord that returns Equal exactly for values that are equal, as sorted collections assume.

Implement behavior directly or derive it

A Rust impl block defines behavior: an inherent impl adds a type’s own methods, while impl Trait for Type connects it to a trait’s operations and laws. For supported standard traits, #[derive(...)] asks the compiler to generate that implementation.

The shown types use Rust’s built-in derives for field-based cloning, comparison and ordering. Each field’s implementation contributes to that behavior.

The generated implementation still has requirements and semantics. Clone, Copy and ordering traits make different promises; choose them from the data and the intended meaning rather than treating derive as a universal default.

01What derive writes

Derived traits use each field’s own implementation

A model-kit shop lists its kits, customizes kits from a template and ranks kits by size. The ranking needs a hand-written comparison when the derived field order differs from the shop’s size-first order.

The shop customizes a kit from a saved template and needs the original to remain unchanged. This reduced kit owns a nested Paint value; follow the clone and later paint update, then predict the recorded Debug/equality line.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Debug, Clone, PartialEq)]

struct Paint {
    tins: u32,
}

#[derive(Debug, Clone, PartialEq)]

struct Kit {
    pieces: u32,
    paint: Paint,
}

fn main() {
    let windmill = Kit {
        pieces: 120,
        paint: Paint { tins: 4 },
    };
    let mut spare = windmill.clone();
    spare.paint.tins = 6;

    println!("{:?} {}", spare, windmill == spare);
}
What is printed?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
rustc --edition=2024 main.rs -o main && ./main

Use the Rust setup from the first reading. Inspect the shown standard derives and field types before predicting each compiler or runtime result.

02Copy

Copy is refused when a field cannot be copied

The listing also carries a text label. Its declaration asks for both explicit Clone and implicit Copy; inspect the String field and predict the compiler’s result.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Debug, Clone, Copy)]

struct Label {
    text: String,
}

fn main() {
    let label = Label {
        text: String::from("tugboat"),
    };
    let other = label;

    println!("{:?} {:?}", label, other);
}
What does rustc do?

03Derived ordering

Derived Ord compares fields in declaration order

Once customized kits can be kept separate, the shop needs a size-ordered listing. First inspect the default ordering the current field layout generates, and predict the names printed by sort.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]

struct Kit {
    name: &'static str,
    pieces: u32,
}

fn main() {
    let mut kits = vec![
        Kit {
            name: "tug",
            pieces: 50,
        },
        Kit {
            name: "barn",
            pieces: 200,
        },
        Kit {
            name: "mill",
            pieces: 120,
        },
    ];
    kits.sort();
    let names: Vec<&str> = kits.iter().map(|kit| kit.name).collect();

    println!("{}", names.join(" "));
}
What is printed?

04Repair the kit shop

Listing, customizing, then ranking

The model-kit shop needs three repairs. First list kits by size. Then customize kits without changing the template. Finally rank kits from largest to smallest, each kit once.

This lab is Rust-only. Each file contains its imports, reader and complete caller.

Repair the kit shop

List by size, detach each customization’s parts, then define a lawful largest-first ranking.

  1. easy · F-DERIVE-V4-1 List the kits
  2. medium · F-DERIVE-V4-2 Customize a kit
  3. hard · F-DERIVE-V4-3 Rank the kits
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.