Deriving Traits
#[derive(...)] asks the compiler to auto-implement standard traits for structs and enums with correct field-wise logic.
Search across all documentation pages
#[derive(...)] asks the compiler to auto-implement standard traits for structs and enums with correct field-wise logic.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct UserId(u64);
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct User {
id: UserId,
name: String,
}When to reach for this: Rapid impl of Debug, Clone, equality, ordering, and serde when field semantics match derived behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Priority { Low, Medium, High }
fn main() {
use std::collections::BTreeSet;
let mut set = BTreeSet::new();
set.insert(Priority::High);
set.insert(Priority::Low);
println!("{:?}", set);
}What this demonstrates:
Ord derive on enums requires discriminant orderingHash + Eq enable HashSet/HashMap keysCopy added when all fields Copyimpl| Trait | Purpose |
|---|---|
Debug | {:?} formatting |
Clone | .clone() duplication |
Copy | Implicit copy (stack bitwise) |
PartialEq/Eq | == equality |
PartialOrd/Ord | sorting comparisons |
Hash | hash maps/sets |
Default | Default::default() |
#[derive(Default)]Picks first variant for enums or requires #[default] attribute on chosen variant (Rust 1.62+).
Display, Drop, From for arbitrary logic - manual impl or separate crates (thiserror, strum).
Eq on floats - Impossible. Fix: Use integers or partial_cmp manually.Ord on floats - Not total order. Fix: Manual impl with partial_cmp wrapper type.Clone cost hidden - Derive clones all fields. Fix: Use Arc inside or avoid Clone.Hash changes with field order - Reordering fields changes hash (same type). Fix: Stable schema versioning for persisted hashes.| Alternative | Use When | Don't Use When |
|---|---|---|
Manual impl | Custom equality/display | Standard structural behavior |
derive_more crate | Boilerplate newtypes | Std derive suffices |
thiserror/strum | Errors/enums strings | Simple structs |
serde derive | JSON/config | No serialization needed |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026