Rust traits and generics: reusable, type-safe code

11 steps · about 6 h 5 min · Intermediate

  1. 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.

  2. Traits & Generics (article, Luca Nerlich, 15 min)

    A short recap that fixes the vocabulary: traits, generics, trait bounds and derive.

  3. 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.

  4. Generics in Rust (article, Serokell, 20 min)

    Covers multiple bounds with +, bounds on structs, and conditional method implementations.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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.