Traits & generics
19 steps in 6 sets of Rust.
Traits are how Rust does polymorphism, and generics are how it stays fast while doing it. The tour covers defining and implementing traits, generic functions and bounds, and the standard traits worth knowing by heart: Display, From, Iterator, Default.
Operator overloading and indexing come next, then dynamic dispatch and the trade against monomorphization. Nineteen steps, and this is the tour that decides whether you can read other people's Rust.
Traits
- TraitsShared behavior a type can implement.
- Default methodsA trait can supply behavior, so implementors only write what differs.
- Associated typesWhen a trait has one type per implementor, an associated type beats a parameter.
Generics
- Generic functions and boundsA type parameter with bounds: one function, every type that satisfies the trait.
- Generic largestA generic function with a trait bound, which is Rust's whole approach to polymorphism in miniature.
- Generic structsA struct over a type parameter, with impl blocks that can be generic or specific.
- impl TraitAnonymous types in signatures: any argument that fits, any return that satisfies.
Standard traits
- From and IntoImplement From and you get Into for free, in both directions of the call.
- Display and DebugDebug is for programmers, Display is for people — derive one, write the other.
- DefaultA canonical empty value, plus struct update syntax to change one field.
- Custom orderingImplementing Ord decides how your type sorts everywhere it is compared.
Operators & access
- Operator overloadingOperators are traits: implement Add and + works on your type.
- Implementing IndexIndex gives your type the square-bracket syntax, borrowing what it returns.
- Deref on a newtypeDeref lets a wrapper forward the inner type's methods without writing any.
- Drop and RAIIDrop runs when a value goes out of scope, which is how Rust does cleanup.
Dynamic dispatch
- Trait objectsA Vec of Box<dyn Trait> holds different concrete types behind one interface.
- Blanket implementationsImplementing a trait for every type that meets a bound — an extension trait.
- Implementing IteratorOne next method and every adapter in the standard library works on your type.
Encore
- shapes.rsTrait objects and generics together: a shape registry that measures and sorts.