Skip to main content
Be Bitwise
RustAdvanced Rust Patterns

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:

rust
use std::fmt;
// Display is a supertrait of PrettyPrint
trait 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:

rust
// Associated type: one implementation per type
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
// Generic parameter: multiple implementations per type
trait ConvertTo<T> {
fn convert(&self) -> T;
}
// A type can implement ConvertTo for many target types
impl ConvertTo<f64> for i32 {
fn convert(&self) -> f64 { *self as f64 }
}
impl ConvertTo<String> for i32 {
fn convert(&self) -> String { self.to_string() }
}
Key Concept

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:

rust
// In your crate: OK - your trait, foreign type
trait MyTrait {}
impl MyTrait for Vec<i32> {}
// In your crate: OK - foreign trait, your type
struct 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> {} // ERROR

That'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:

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

Try itUncomment the impl for Vec<String> and run it to meet the orphan rule's error, E0117.
Rust (1.40.0)

Blanket Implementations

A blanket impl applies a trait to every type satisfying some bound, all at once:

rust
trait Greet {
fn greet(&self) -> String;
}
// Blanket implementation: any type that implements Display also gets Greet
impl<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 String
  • impl<T> From<T> for T - every type can be converted from itself
  • impl<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:

rust
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, or self receiver, or have where Self: Sized bounds
  • No methods return Self (unless bounded by Sized)
  • No generic method parameters
rust
// Object-safe
trait Drawable {
fn draw(&self);
}
// NOT object-safe (returns Self)
trait Clonable {
fn clone_self(&self) -> Self;
}
// Workaround: make the non-object-safe method require Sized
trait 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:

Try itCall .sum_of_squares() on (1u8..=10) too: u8 converts into i64, so the blanket impl already covers it.
Rust (1.40.0)

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.

Rust (1.40.0)