Skip to content
RustLearn

Module 12 — Traits & Trait Objects

Goal

Shared behavior without inheritance. Trait definitions, default methods, blanket impls, the orphan rule, and static vs dynamic dispatch.

Start here — what this module is really about

A trait is a set of behaviours a type can promise to provide. If you come from an object-oriented language, the nearest thing you know is an interface — but the differences matter more than the similarity.

rust
trait Summary {
    fn summarize(&self) -> String;
}

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

Notice what did not happen: Article was not declared as "a kind of Summary" when it was defined. The implementation is a separate statement, written anywhere in the crate, possibly long afterwards. That is the first real difference — traits are opted into after the fact, not baked into a type's definition. You can implement your own trait for i32, or for Vec<String>, without touching the standard library.

Inheritance asks what is this thing descended from? — a decision made once, at definition, permanently. A trait asks what can this thing do? — a question answered as many times as you like, by anyone. Rust has no inheritance at all, and traits are what fills the gap.

The second big idea in this module is two ways of using a trait:

  • Static dispatch (impl Trait, or a generic with a bound): the compiler knows the concrete type at each call site and generates specialised code. Fast, and every value in a collection must be the same type.
  • Dynamic dispatch (dyn Trait, usually inside a Box): the concrete type is only known at runtime, and each call looks up the right function through a table. Slightly slower, and it lets a single list hold several different types that all implement the trait.

Most of the standard library's vocabulary — Display, Debug, Clone, Iterator, From — is traits. Learning to implement them is how your types stop feeling foreign in Rust code.

The one sentence to remember: a trait is a capability a type can be granted at any time, and you choose per use whether the compiler resolves it (fast, one type) or the program does (flexible, many types).

Learning objectives

  • Define traits with required and default methods
  • Implement traits for your own and foreign types; understand the orphan rule
  • Distinguish static dispatch (impl Trait, generics) from dynamic dispatch (dyn Trait)
  • Use associated types, supertraits, and operator overloading
  • Implement the standard traits every Rust type should consider

12.1 Defining and implementing

A trait is a set of method signatures a type can implement — an interface, with more power.

rust
pub trait Summary {
    fn summarize_author(&self) -> String;          // required

    fn summarize(&self) -> String {                // default implementation
        format!("(Read more from {}...)", self.summarize_author())
    }
}

pub struct Tweet { pub username: String, pub content: String }

impl Summary for Tweet {
    fn summarize_author(&self) -> String {
        format!("@{}", self.username)
    }
    // summarize() comes for free
}

pub struct Article { pub headline: String, pub author: String }

impl Summary for Article {
    fn summarize_author(&self) -> String { self.author.clone() }
    fn summarize(&self) -> String {                // override the default
        format!("{}, by {}", self.headline, self.author)
    }
}

Default methods can call required methods — that's how you build a large API on a small required surface. Iterator is the extreme example: you implement next(), and get ~75 methods free.

The orphan rule

You may implement a trait for a type only if the trait or the type is local to your crate.

rust
impl Summary for Vec<i32> {}      // ✅ Summary is mine
impl Display for MyStruct {}      // ✅ MyStruct is mine
// impl Display for Vec<i32> {}   // ❌ both are foreign

This guarantees coherence: there is exactly one implementation of a trait for a type in the whole program, so adding a dependency can never silently change behaviour.

Workaround: the newtype pattern.

rust
use std::fmt;

struct Wrapper(Vec<String>);

impl fmt::Display for Wrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

Analogy — the qualification, not the family tree

Inheritance asks what is this thing descended from? — a family tree you must decide up front and can never revise. A trait asks what can this thing do? — a qualification any type can earn later, including types you did not write. It is the difference between being born into the guild and passing its exam.

12.2 Traits as parameters — static dispatch

rust
pub fn notify(item: &impl Summary) {
    println!("Breaking! {}", item.summarize());
}

// identical, but the type parameter is nameable:
pub fn notify<T: Summary>(item: &T) { }

// two params forced to the SAME type:
pub fn compare<T: Summary>(a: &T, b: &T) { }

// two params of possibly different types:
pub fn compare2(a: &impl Summary, b: &impl Summary) { }

These are monomorphized (module 11): the call is resolved at compile time, can be inlined, and costs nothing.

12.3 Trait objects — dynamic dispatch

When the concrete type isn't known until runtime, use dyn Trait behind a pointer:

rust
pub trait Draw {
    fn draw(&self);
}

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,     // heterogeneous!
}

impl Screen {
    pub fn run(&self) {
        for component in &self.components {
            component.draw();               // vtable lookup at runtime
        }
    }
}

struct Button { label: String }
struct Checkbox { checked: bool }

impl Draw for Button { fn draw(&self) { println!("[{}]", self.label); } }
impl Draw for Checkbox { fn draw(&self) { println!("[{}]", if self.checked {"x"} else {" "}); } }

fn main() {
    let screen = Screen {
        components: vec![
            Box::new(Button { label: "OK".into() }),
            Box::new(Checkbox { checked: true }),
        ],
    };
    screen.run();
}

A &dyn Trait is a fat pointer: one word to the data, one word to a vtable of function pointers.

Static vs dynamic dispatch

impl Trait / genericsdyn Trait
Dispatchcompile timeruntime (vtable)
Costzero, inlinableone indirect call, no inlining
Binary sizeone copy per typeone copy total
Compile timeslowerfaster
Heterogeneous collections❌✅
Type known atcompile timeruntime

Default to generics; reach for dyn when you need heterogeneity, when the type is chosen at runtime, or when compile time and binary size matter more than the last nanosecond.

Object safety

Not every trait can become a dyn Trait. A trait is object safe if:

  • No method returns Self
  • No method has generic type parameters
  • No Sized requirement on Self
rust
trait NotObjectSafe {
    fn clone_me(&self) -> Self;         // ❌ returns Self
    fn generic<T>(&self, x: T);         // ❌ generic method
}

Why: a vtable has one entry per method, but a generic method has infinitely many instantiations, and -> Self has no known size at the call site. Fix by returning Box<dyn Trait> or moving the generic method to a separate trait or an where Self: Sized bound.


impl Trait vs dyn Trait, and when each is right

Same trait, two ways to accept it:

rust
trait Draw { fn draw(&self); }

// Static dispatch: one concrete type per call site, resolved at compile time.
fn render_static(item: &impl Draw) { item.draw(); }

// Dynamic dispatch: any Draw, decided at runtime.
fn render_dynamic(item: &dyn Draw) { item.draw(); }

The difference becomes forced — not a preference — the moment you want a collection:

rust
// ❌ Does not compile: every element of a Vec must be the same type.
let shapes: Vec<impl Draw> = vec![circle, square];

// ✅ Works: each element is a pointer to *some* Draw, on the heap.
let shapes: Vec<Box<dyn Draw>> = vec![Box::new(circle), Box::new(square)];

Why the second one needs Box: a Vec stores elements of one fixed size, and a Circle and a Square may be different sizes. Box<dyn Draw> is a pointer — always the same size — pointing at the real value on the heap. Alongside it, Rust keeps a second pointer to a vtable, a small table of that type's method addresses, which is how the right draw gets called.

How to choose:

  • Default to static dispatch (impl Trait or generics). It is faster and it is what most Rust code uses.
  • Reach for dyn when the types genuinely vary at runtime — plugin lists, heterogeneous collections, callbacks stored in a struct — or when monomorphization is bloating compile times.

The performance gap is one pointer indirection per call and no inlining. Real, but for most code far smaller than the design freedom is worth.

Analogy — the crew list versus the mixed team

Static dispatch is hiring a crew of identical specialists: the compiler knows exactly who does the work and can plan around it. A trait object is a mixed team behind one job description — you hold a clipboard listing who is on site, and each person's actual method is looked up when you call them. You pay one small lookup for the freedom to put different types on the same list.

12.4 Associated types

rust
pub trait Iterator {
    type Item;                             // an associated type
    fn next(&mut self) -> Option<Self::Item>;
}

struct Counter { count: u32 }

impl Iterator for Counter {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        if self.count < 5 { self.count += 1; Some(self.count) } else { None }
    }
}

Why not a generic trait Iterator<T>? Because a type should have one iterator item type. With a generic parameter you could write impl Iterator<u32> for Counter and impl Iterator<String> for Counter, and every call site would need annotation. Associated types say "this is determined by the implementing type", which keeps inference clean.

Rule of thumb

If the implementing type determines the type, use an associated type. If the caller should choose, use a generic parameter (like From<T>, where a type can convert from many sources).

12.5 Supertraits

rust
use std::fmt;

trait OutlinePrint: fmt::Display {         // requires Display
    fn outline_print(&self) {
        let output = self.to_string();     // available because of the supertrait
        let len = output.len();
        println!("{}", "*".repeat(len + 4));
        println!("*{}*", " ".repeat(len + 2));
        println!("* {output} *");
        println!("*{}*", " ".repeat(len + 2));
        println!("{}", "*".repeat(len + 4));
    }
}

Any type implementing OutlinePrint must also implement Display.

12.6 Operator overloading

Operators are traits:

rust
use std::ops::Add;

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

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

// mixed-type addition
impl Add<i32> for Point {
    type Output = Point;
    fn add(self, n: i32) -> Point { Point { x: self.x + n, y: self.y + n } }
}

fn main() {
    assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 });
    assert_eq!(Point { x: 1, y: 1 } + 5, Point { x: 6, y: 6 });
}

Other operator traits: Sub, Mul, Div, Rem, Neg, Not, AddAssign, Index, IndexMut, Deref, DerefMut.

12.7 The standard traits worth knowing

TraitPurposeDerivable?
Debug{:?} output for programmers✅
Display{} output for users❌
Clone / Copyduplication✅
PartialEq / Eqequality✅
PartialOrd / Ordordering, sorting✅
Hashhash map keys✅
DefaultT::default()✅
From / Intoinfallible conversion❌
TryFrom / TryIntofallible conversion❌
Iteratoriteration❌
IntoIteratorusable in for❌
FromStr"x".parse::<T>()❌
AsRef<T>cheap reference conversion❌
Derefsmart pointer transparency❌
Dropdestructor❌
Send / Syncthread safety markersauto

From gives you Into free

rust
struct Celsius(f64);
struct Fahrenheit(f64);

impl From<Celsius> for Fahrenheit {
    fn from(c: Celsius) -> Self { Fahrenheit(c.0 * 9.0 / 5.0 + 32.0) }
}

let f: Fahrenheit = Celsius(100.0).into();       // Into is blanket-implemented
let f = Fahrenheit::from(Celsius(100.0));

Implement From, never Into. The blanket impl impl<T, U: From<T>> Into<U> for T handles the rest — and this is also what makes ? convert error types (module 08).

FromStr gives you .parse()

rust
use std::str::FromStr;

struct Rgb(u8, u8, u8);

impl FromStr for Rgb {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.strip_prefix('#').ok_or("missing #")?;
        if s.len() != 6 { return Err("need 6 hex digits".into()); }
        let p = |i: usize| u8::from_str_radix(&s[i..i+2], 16).map_err(|e| e.to_string());
        Ok(Rgb(p(0)?, p(2)?, p(4)?))
    }
}

let c: Rgb = "#ff8800".parse().unwrap();

The standard traits, and what implementing them buys you

Rust's ecosystem is held together by a handful of traits. Implementing them is how your type becomes a good citizen:

TraitWhat it enablesHow you usually get it
Debug{:?} printing for developers#[derive(Debug)]
Display{} printing for usersWritten by hand — Rust will not guess
CloneExplicit deep copies#[derive(Clone)]
PartialEq / Eq== and !=#[derive(PartialEq)]
PartialOrd / Ord<, >, sorting#[derive(PartialOrd)]
DefaultType::default()#[derive(Default)]
From / IntoConversions, and ? error conversionWritten by hand
Iteratorfor loops and the whole adaptor toolkitWritten by hand (module 14)

Two details worth knowing now:

  • Display is never derived, Debug always can be. That is deliberate: how a type should look to an end user is a design decision no compiler can make, while a developer-facing dump is mechanical.
  • Implement From, get Into free. impl From<A> for B automatically gives you a.into() producing a B, via a blanket implementation in the standard library. Write the one, get both — and error conversion with ? starts working (module 08).

Analogy — the standard fittings

Display, Debug, From, Iterator, Default are the standard fittings of the Rust ecosystem — the equivalent of a plug that fits every socket in the country. Implementing them is not ceremony; it is what lets your type be printed, converted, looped over and slotted into other people's code without adapters.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
traitA set of behaviours a type can implement.
implementTo provide a trait's methods for a specific type, in an impl Trait for Type block.
default methodA method the trait itself provides, which implementors may override.
static dispatchThe compiler resolves which function runs, at compile time. Fast.
dynamic dispatchThe program resolves it at runtime through a table. Flexible.
trait objectdyn Trait, usually behind a Box or & — a value whose concrete type is not known at compile time.
vtableThe lookup table of method addresses used by dynamic dispatch.
associated typeA type chosen by the implementor, like Iterator's Item.
supertraitA trait that requires another: trait Admin: User.
blanket implementationImplementing a trait for every type satisfying a bound: impl<T: Display> ToString for T.
orphan ruleYou may implement a trait for a type only if you own one of the two. Prevents conflicting impls.
object safetyThe property a trait needs to be usable as dyn Trait — roughly, no generic methods, no Self returns.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0277]: doesn't implement DisplayYou used {} on a type that has no user-facing format.Use {:?} with #[derive(Debug)], or implement Display yourself.
error[E0117]: only traits defined in the current crate can be implemented for types defined outsideThe orphan rule: both the trait and the type are foreign.Wrap the foreign type in your own struct (the newtype pattern) and implement on that.
error[E0038]: the trait cannot be made into an objectYou used dyn Trait on a trait that is not object safe.Remove generic methods or Self return types, or use generics instead of dyn.
error[E0782]: expected a type, found a traitYou wrote a bare trait name where a type belongs.Write &dyn Trait, Box<dyn Trait>, or impl Trait.
error[E0308]: mismatched types inside a Vec of mixed typesEvery Vec element must be one type.Vec<Box<dyn Trait>>.

Now make it stick: work through the drills for this module, then carry on to Module 13 — Lifetimes.