Common Standard Traits
Standard library traits appear everywhere. Know Debug, Display, Clone, Copy, Eq, Ord, Hash, Default, From/Into, and Deref.
Recipe
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
struct UserId(u64);
fn main() {
let mut m = HashMap::new();
m.insert(UserId(1), "Ada");
let id: UserId = 2u64.into();
println!("{:?} {}", UserId::default(), id.0);
}When to reach for this: Collections keys, logging, conversions, and smart pointer ergonomics.
Working Example
#[derive(Debug, Default, PartialEq)]
struct Config { timeout_ms: u64, retries: u32 }
impl From<u64> for Config {
fn from(timeout_ms: u64) -> Self {
Self { timeout_ms, ..Default::default() }
}
}
fn main() {
let c: Config = 5000.into();
assert_eq!(c.timeout_ms, 5000);
}What this demonstrates:
Default+Fromfor ergonomic constructionIntoauto fromFromPartialEqfor testsDebugfor diagnostics
Deep Dive
| Trait | Role |
|---|---|
From/Into | Type conversions |
AsRef/AsMut | Cheap reference views |
Borrow/BorrowMut | Hash map key borrowing |
ToOwned | Clone to owned counterpart |
Deref/DerefMut | Smart pointer coercion |
Gotchas
- Derive
Ordon floats - Not total. Fix: Wrapper or integer cents. HashwithoutEq- Derive pairing. Fix: Both together for maps.Displaynot derivable - Manual impl needed. Fix: UseDebugor writefmt.Defaultwrong sentinel - Zero values misleading. Fix:new()constructor instead.Fromoverlap - Only oneFrom<T>per type. Fix: Newtype for ambiguous sources.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Constructor fn | Default misleading | Default is natural zero |
TryFrom | Fallible convert | Infallible From |
Manual Hash | Custom key logic | Derive works |
FAQs
Clone vs Copy?
Copy implicit; Clone explicit deep copy.Eq vs PartialEq?
Eq requires reflexive total equality.Ord vs PartialOrd?
Ord total ordering.AsRef str?
String implements AsRefBorrow for HashMap?
Lookup with &str for String keys via Borrow.Send/Sync?
Auto traits for thread safety.Drop?
Cleanup - not derivable with Copy.Iterator trait?
Separate from Eq/Hash family.serde traits?
Serialize/Deserialize from serde crate.Read trait catalog?
docs.rs std::prelude::rust_2024 for current set.Related
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+.