Rust traits and generics: reusable, type-safe code
11 steps · about 6 h 5 min · Intermediate
- Generic Types, Traits, and Lifetimes - The Rust Programming Language (doc, The Rust Programming Language (official book), 1 h)
The official book is the best place to start. It builds from removing duplication to generics and then traits.
- Traits & Generics (article, Luca Nerlich, 15 min)
A short recap that fixes the vocabulary: traits, generics, trait bounds and derive.
- Bounds - Rust By Example (reference, Rust By Example, 15 min)
Runnable examples show how a bound lets generic code call a trait's methods, and what the compiler error looks like without one.
- Generics in Rust (article, Serokell, 20 min)
Covers multiple bounds with +, bounds on structs, and conditional method implementations.
- Uncovering Rust: Traits and Generics (article, Andy Pearce, 25 min)
Moves on to where clauses and associated types, which you need for reading real library signatures.
- An introduction to advanced Rust traits and generics (article, Shuttle, 15 min)
Shows supertraits and bounds like Send + Sync + Clone in a real-world setting, the Axum FromRequest trait.
- Traits — Rust Tutorial (tutorial, LearnCodingFast, 30 min)
Practice exercises and a quiz let you check that you can write traits, default methods and impl Trait yourself.
- dyn Trait and impl Trait in Rust (article, Nick Cameron, 20 min)
Explains how trait objects work (fat pointers, no monomorphisation) and the trade-offs against impl Trait.
- Trait Objects and Dynamic Dispatch - The Rust How-to Book (guide, The Rust How-to Book, 20 min)
Practical patterns for storing mixed types as trait objects, plus the object-safety rules.
- Item 12: Understand the trade-offs between generics and trait objects - Effective Rust (article, Effective Rust (David Drysdale), 25 min)
Gives design guidance on when to pick generics and when to pick trait objects.
- Crust of Rust: Dispatch and Fat Pointers (video, Jon Gjengset (YouTube), 2 h)
The last step is a deep dive into monomorphization, vtables and fat pointers, which explains why the earlier rules exist.