Advanced Traits
Traits are how Rust shares behaviour across types. Earlier modules covered the basics — defining traits, implementing them, using them as bounds. Time to push further: supertraits, associated types, the orphan rule, blanket impls.
Supertraits
A supertrait is a trait that requires another trait to be implemented first:
use std::fmt;
// Display is a supertrait of PrettyPrinttrait PrettyPrint: fmt::Display { fn pretty_print(&self) { println!("=== {} ===", self); // Can use Display because it is required }}
struct Point { x: f64, y: f64,}
impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) }}
impl PrettyPrint for Point {}
fn main() { let p = Point { x: 1.0, y: 2.0 }; p.pretty_print(); // === (1, 2) ===}No Display, no PrettyPrint. The compiler won't even let you try.
Associated Types vs Generic Parameters
Both associated types and generics parameterise traits. They pull in different directions, though:
// Associated type: one implementation per typetrait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>;}
// Generic parameter: multiple implementations per typetrait ConvertTo<T> { fn convert(&self) -> T;}
// A type can implement ConvertTo for many target typesimpl ConvertTo<f64> for i32 { fn convert(&self) -> f64 { *self as f64 }}
impl ConvertTo<String> for i32 { fn convert(&self) -> String { self.to_string() }}Reach for associated types when one implementation is the obvious fit — an iterator yields one item type, full stop. Reach for generic parameters when several make sense, like a value converting to many target types. Associated types also keep call sites tidier.
The Orphan Rule (Trait Coherence)
Rust enforces the orphan rule: an impl only flies if either the trait or the type lives in your crate. The point is to stop two crates from defining clashing implementations:
// In your crate: OK - your trait, foreign typetrait MyTrait {}impl MyTrait for Vec<i32> {}
// In your crate: OK - foreign trait, your typestruct MyType;impl std::fmt::Display for MyType { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "MyType") }}
// FORBIDDEN: foreign trait, foreign type// impl std::fmt::Display for Vec<i32> {} // ERRORThat's the short version. The full rule in the Rust Reference has two extra wrinkles: a bare generic parameter can't appear before the first local type (so impl<T> From<MyType> for T is rejected with E0210, while impl<T> From<MyType> for Vec<T> is fine), and "fundamental" wrappers such as &T, &mut T, Box<T> and Pin<T> count as local when T is.
The newtype pattern works around this:
struct Wrapper(Vec<String>);
impl std::fmt::Display for Wrapper { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[{}]", self.0.join(", ")) }}The runner holds both versions. Only one of them compiles.
Blanket Implementations
A blanket impl applies a trait to every type satisfying some bound, all at once:
trait Greet { fn greet(&self) -> String;}
// Blanket implementation: any type that implements Display also gets Greetimpl<T: std::fmt::Display> Greet for T { fn greet(&self) -> String { format!("Hello, {}!", self) }}
fn main() { println!("{}", "world".greet()); // Hello, world! println!("{}", 42.greet()); // Hello, 42!}The standard library uses blanket implementations extensively:
impl<T: Display> ToString for T- anything displayable can be converted to Stringimpl<T> From<T> for T- every type can be converted from itselfimpl<T: ?Sized> Borrow<T> for T- every type can borrow itself
Trait Objects and Dynamic Dispatch
When you need a mixed bag of types behaving uniformly:
trait Shape { fn area(&self) -> f64; fn name(&self) -> &str;}
struct Circle { radius: f64 }struct Rectangle { width: f64, height: f64 }
impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius } fn name(&self) -> &str { "Circle" }}
impl Shape for Rectangle { fn area(&self) -> f64 { self.width * self.height } fn name(&self) -> &str { "Rectangle" }}
fn print_shapes(shapes: &[Box<dyn Shape>]) { for shape in shapes { println!("{}: area = {:.2}", shape.name(), shape.area()); }}
fn main() { let shapes: Vec<Box<dyn Shape>> = vec![ Box::new(Circle { radius: 5.0 }), Box::new(Rectangle { width: 3.0, height: 4.0 }), ]; print_shapes(&shapes);}Object Safety
Not all traits can be used as trait objects. A trait is object-safe (newer Rust documentation says dyn compatible) if:
- It does not require
Self: Sized - All methods either have a
&self,&mut self, orselfreceiver, or havewhere Self: Sizedbounds - No methods return
Self(unless bounded bySized) - No generic method parameters
// Object-safetrait Drawable { fn draw(&self);}
// NOT object-safe (returns Self)trait Clonable { fn clone_self(&self) -> Self;}
// Workaround: make the non-object-safe method require Sizedtrait SmartClone { fn clone_self(&self) -> Self where Self: Sized; fn draw(&self);}Extension Traits
Bolt new methods onto existing types with a fresh trait and a blanket impl:
Crates like itertools lean on this pattern to bolt extra adapters onto the standard Iterator.
Challenges
Implement an iterator that yields the Fibonacci sequence up to a limit. Create a Fibonacci struct, implement Iterator for it, then use it to print the sum of Fibonacci numbers below 100.