Derive and semantic contracts
Quick answer
Derive generates implementations for supported traits from a type's definition. It saves boilerplate, but the meaning of the generated behavior still matters for your domain.
Fields determine generated behavior
#[derive(Debug, PartialEq, Eq, Hash)] can generate field-based implementations when all fields support the relevant traits. Equal values must hash equally. Derived ordering follows declared field order for structs; do not use it as business priority unless that order matches your policy.
use std::collections::HashSet;#[derive(PartialEq, Eq, Hash)]struct Key { room: u32, seat: u32 }fn main() { let mut keys = HashSet::new(); keys.insert(Key { room: 1, seat: 2 }); println!("{}", keys.contains(&Key { room: 1, seat: 2 }));}Expected stdout (not executed):
trueEquality and hashing agree for the two fields.
#[derive(PartialEq, Eq, PartialOrd, Ord)]struct Slot { day: u32, hour: u32 }fn main() { println!("{}", Slot { day: 1, hour: 9 } < Slot { day: 2, hour: 1 }); }Expected stdout (not executed):
trueDay is compared before hour.
Common mistake
Do not derive equality over metadata if your domain defines identity using only an ID.
Try it yourself
Design an identity key for a library book copy and decide which fields should participate in equality.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Derive and semantic contracts — practice quiz
Choose one answer per question, then review the explanation.
What happens when deriving PartialEq on a struct with two comparable fields?
Must two unequal keys always have different hashes?
When deriving Ord for a struct, what normally determines field comparison priority?