Traits & Generics

Shared behaviour with traits, default methods, generics and trait bounds, impl Trait, static dispatch (monomorphisation) vs dynamic dispatch (dyn Trait), associated types, operator overloading, derive, and the orphan rule.

Intermediate 3 min readLesson 5 of 9

Traits define shared behaviour — like interfaces in Java or protocols in Swift. Generics let code work over many types. Together they give Rust zero-cost polymorphism: generic code is specialised at compile time and runs as fast as hand-written code for each type.

Defining and implementing traits

Rust
trait Summary {
    fn author(&self) -> String;                  // required method

    fn summarize(&self) -> String {              // default method (can be overridden)
        format!("(Read more from {}…)", self.author())
    }
}

struct Article { title: String, author: String }
struct Tweet { username: String, content: String }

impl Summary for Article {
    fn author(&self) -> String { self.author.clone() }
    fn summarize(&self) -> String { format!("{} by {}", self.title, self.author) }
}

impl Summary for Tweet {
    fn author(&self) -> String { format!("@{}", self.username) }   // uses the default summarize
}

You can implement traits for types you didn't write (e.g. your trait for Vec<T>), and foreign traits for your types (e.g. Display for Article) — but not a foreign trait for a foreign type (the orphan rule, which keeps implementations coherent across crates). Wrap the type in a newtype to work around it.

Generics with trait bounds

Rust
// Works for any T that implements Summary
fn notify<T: Summary>(item: &T) {
    println!("Breaking! {}", item.summarize());
}

// Equivalent shorthand
fn notify2(item: &impl Summary) { /* ... */ }

// Multiple bounds and where clauses
fn report<T, U>(a: &T, b: &U) -> String
where
    T: Summary + Clone,
    U: std::fmt::Display + PartialOrd,
{
    format!("{} / {}", a.summarize(), b)
}

// Generic structs and impls
struct Pair<T> { a: T, b: T }

impl<T: PartialOrd + std::fmt::Display> Pair<T> {
    fn largest(&self) -> &T {
        if self.a > self.b { &self.a } else { &self.b }
    }
}

fn max<T: PartialOrd + Copy>(items: &[T]) -> Option<T> {
    let mut it = items.iter().copied();
    let first = it.next()?;
    Some(it.fold(first, |m, x| if x > m { x } else { m }))
}

Static dispatch: monomorphisation

For generic functions, the compiler generates a separate copy for each concrete type used — max::<i32>, max::<f64> — and calls are resolved at compile time and can be inlined. That's zero-cost abstraction: no runtime lookups. The trade-off is larger binaries and longer compile times.

Dynamic dispatch: trait objects

Sometimes you need a collection of different types sharing a trait, decided at runtime. Use a trait object, dyn Trait, behind a pointer:

Rust
let feed: Vec<Box<dyn Summary>> = vec![
    Box::new(Article { title: "Rust 2.0".into(), author: "Ferris".into() }),
    Box::new(Tweet { username: "rustlang".into(), content: "hi".into() }),
];

for item in &feed {
    println!("{}", item.summarize());          // resolved at runtime via a vtable
}

fn print_all(items: &[&dyn Summary]) { /* ... */ }

A trait object is a fat pointer: a pointer to the data plus a pointer to a vtable of the type's method implementations — the same mechanism as C++ virtual functions (OOP fundamentals).

Generics (T: Trait, impl Trait)Trait objects (dyn Trait)
DispatchStatic, at compile timeDynamic, via vtable
PerformanceInlinable, fastestAn indirect call; no inlining
Heterogeneous collectionsNo (one T per instantiation)Yes
Binary sizeGrows with each instantiationOne copy
Restrictions—Must be "dyn compatible" (no generic methods, no returning Self by value)

Returning traits

Rust
fn make_counter() -> impl Iterator<Item = u32> {     // some concrete type, hidden from the caller
    (1..).step_by(2).take(5)
}

fn make_shape(kind: &str) -> Box<dyn Shape> {        // different types at runtime → trait object
    match kind {
        "circle" => Box::new(Circle::new(1.0)),
        _ => Box::new(Square::new(1.0)),
    }
}

impl Trait in return position must be a single concrete type; use Box<dyn Trait> when it varies.

Associated types

A trait can declare a type that each implementation chooses — cleaner than a generic parameter when there's one natural choice per implementor:

Rust
trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

struct Countdown(u32);
impl Iterator for Countdown {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        if self.0 == 0 { None } else { self.0 -= 1; Some(self.0 + 1) }
    }
}
// Implementing next() gives you map, filter, sum, collect… for free (default methods)
let total: u32 = Countdown(3).sum();    // 6

Standard traits worth knowing

TraitPurposeUsually
Debug{:?} formatting#[derive(Debug)]
Display{} user-facing formattingImplement by hand
Clone / CopyExplicit / implicit duplicationderive
PartialEq / Eq, PartialOrd / OrdComparisonderive
HashUse as HashMap keyderive (with Eq)
DefaultA default valuederive or implement
From / IntoConversions (String::from, .into())Implement From
Iterator / IntoIteratorfor loops and adaptersImplement next
DropCleanupImplement
DerefSmart-pointer behaviourSmart pointers
Send / SyncThread safety markersAuto-implemented (Concurrency)
Add, Mul, Index…Operator overloadingImplement
Rust
use std::fmt;
use std::ops::Add;

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 { x: f64, y: f64 }

impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, o: Vec2) -> Vec2 { Vec2 { x: self.x + o.x, y: self.y + o.y } }
}

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({:.1}, {:.1})", self.x, self.y)
    }
}

println!("{}", Vec2 { x: 1.0, y: 2.0 } + Vec2 { x: 3.0, y: 4.0 });   // (4.0, 6.0)
Key takeaways
  • Traits define shared behaviour, with optional default methods; the orphan rule keeps impls coherent.
  • Generic functions with trait bounds are monomorphised: static dispatch, zero cost, bigger binaries.
  • dyn Trait behind a pointer gives dynamic dispatch via vtables, enabling heterogeneous collections.
  • impl Trait hides one concrete type; Box of dyn Trait allows varying types.
  • Associated types (like Iterator::Item) and default methods make traits powerful.
  • Derive common traits; implement Display, From, and operator traits as needed.