← Rust Programming learning path
Rust Programming · Module 8 of 10

Traits and generics

Share behaviour with traits and write generic code.

📖 Key ideas

  1. A trait defines shared behaviour: trait Summary { fn summarize(&self) -> String; }.
  2. impl Summary for Article { ... }.
  3. Generics: fn largest<T: PartialOrd>(list: &[T]) -> &T.
  4. Trait bounds restrict generic types.
  5. Common traits: Debug, Clone, Display, Iterator.
💡 Real-life example: Traits are skill badges: any type that earns the badge can perform that skill.
TraitShared behaviour definition
Trait boundConstraint on a generic type
GenericType parameter <T>
DisplayTrait for user-facing printing