Skip to content
LumenaryAcademy
Practice 60 min

Traits and generics

Shared behaviour without inheritance, code that works for many types at no run-time cost, and dynamic dispatch when you need it.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Code that works for many types

Sooner or later you write the same function twice. You need the overlap of two time ranges in hours and of two temperature ranges in degrees; you want to send an alert by SMS and by email; you want + to work on your own fraction type the way it works on integers. Copying code for each type is tedious and error-prone. Object-oriented languages answer with class hierarchies; dynamic languages answer with "just call the method and hope it's there".

Rust's answer has two parts. A trait names a set of behaviour, such as "can be displayed", "can be added", "can send a notification", that any type may implement. Generics let you write functions and types with placeholders for types, constrained by traits: "this works for any T that can be compared". The compiler checks every use against those constraints, so mistakes are compile errors with clear messages, not crashes in production.

And because the compiler produces specialised machine code for each concrete type you use, generic code runs exactly as fast as code written by hand for that type. When you genuinely need a collection of different types behind one interface, trait objects provide dynamic dispatch, explicitly marked with the keyword dyn so that you can always see which kind you are using. Almost every abstraction in the standard library, from println! to iterators to threads, is built from these pieces.

DefinitionsH

Defining and implementing traits

Definition— trait

A trait declares methods that implementing types must provide (required methods) and may supply ready-made ones built on top of them (provided or default methods). impl TraitName for TypeName { ... } implements a trait for a type. A trait bound such as T: Instrument restricts a generic type parameter to types that implement the trait.

rust
trait Instrument {
    // Required methods: every implementation must provide these.
    fn name(&self) -> String;
    fn strings(&self) -> u32;

    // A provided (default) method, built on the required ones.
    fn describe(&self) -> String {
        format!("the {} has {} strings", self.name(), self.strings())
    }
}

struct Kora;

struct Guitar {
    strings: u32,
}

struct Sitar {
    sympathetic: u32,
}

impl Instrument for Kora {
    fn name(&self) -> String {
        String::from("kora")
    }
    fn strings(&self) -> u32 {
        21
    }
}

impl Instrument for Guitar {
    fn name(&self) -> String {
        match self.strings {
            6 => String::from("guitar"),
            n => format!("{n}-string guitar"),
        }
    }
    fn strings(&self) -> u32 {
        self.strings
    }
}

impl Instrument for Sitar {
    fn name(&self) -> String {
        String::from("sitar")
    }
    fn strings(&self) -> u32 {
        7 + self.sympathetic
    }
    // Overriding the default method.
    fn describe(&self) -> String {
        format!(
            "the sitar has 7 playing strings and {} sympathetic ones",
            self.sympathetic
        )
    }
}

// A generic function: works for any type T that implements Instrument.
fn total_strings<T: Instrument>(section: &[T]) -> u32 {
    let mut total = 0;
    for instrument in section {
        total += instrument.strings();
    }
    total
}

// `impl Trait` in argument position is shorthand for the same thing.
fn announce(instrument: &impl Instrument) {
    println!("Now playing: {}", instrument.describe());
}

fn main() {
    announce(&Kora);
    announce(&Guitar { strings: 12 });
    announce(&Sitar { sympathetic: 13 });

    let guitars = [
        Guitar { strings: 6 },
        Guitar { strings: 12 },
        Guitar { strings: 7 },
    ];
    println!("the guitar section has {} strings", total_strings(&guitars));
}
text
Now playing: the kora has 21 strings
Now playing: the 12-string guitar has 12 strings
Now playing: the sitar has 7 playing strings and 13 sympathetic ones
the guitar section has 25 strings

The trait Instrument is a contract with two required methods and one provided method. Kora and Guitar accept the default describe; Sitar overrides it. Kora is a unit struct, with no fields at all, which is perfectly fine for implementing a trait.

total_strings<T: Instrument> reads "for any type T that implements Instrument". Inside, the only things you may do with a T are what the bound allows, so instrument.strings() compiles but instrument.colour() would not, even if every type you happen to pass has a colour method. This is the key difference from C++ templates or duck typing: a generic function is checked once, against its bounds, not separately for each call. The parameter &[T] holds one type at a time; a slice mixing kora and guitars is impossible here, and the last section of the lesson shows the alternative.

announce(instrument: &impl Instrument) uses impl Trait in argument position, a shorter way to write the same kind of generic function when the type parameter is used only once. Bounds can combine several traits with + (T: Instrument + Clone), and when bounds get long they move into a where clause after the signature, as you will see below.

Worked examplesH

Standard traits: making your types feel built in

Much of Rust's syntax is sugar over standard traits. {} calls Display, == calls PartialEq, a + b calls Add::add, .into() uses From, and for loops use IntoIterator. Implement the trait and your type joins in. Here is a fraction type that reduces itself to lowest terms:

rust
use std::fmt;
use std::ops::{Add, Mul};

/// A fraction kept in lowest terms with a positive denominator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Fraction {
    num: i64,
    den: i64,
}

fn gcd(a: i64, b: i64) -> i64 {
    if b == 0 { a.abs() } else { gcd(b, a % b) }
}

impl Fraction {
    fn new(num: i64, den: i64) -> Fraction {
        assert!(den != 0, "denominator must not be zero");
        let sign = if den < 0 { -1 } else { 1 };
        let g = gcd(num, den);
        Fraction {
            num: sign * num / g,
            den: sign * den / g,
        }
    }
}

// Display: how the value looks to users, used by {}.
impl fmt::Display for Fraction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.den == 1 {
            write!(f, "{}", self.num)
        } else {
            write!(f, "{}/{}", self.num, self.den)
        }
    }
}

// Operator overloading: a + b calls Add::add(a, b).
impl Add for Fraction {
    type Output = Fraction;
    fn add(self, other: Fraction) -> Fraction {
        Fraction::new(
            self.num * other.den + other.num * self.den,
            self.den * other.den,
        )
    }
}

impl Mul for Fraction {
    type Output = Fraction;
    fn mul(self, other: Fraction) -> Fraction {
        Fraction::new(self.num * other.num, self.den * other.den)
    }
}

// Conversion: every integer is a fraction.
impl From<i64> for Fraction {
    fn from(n: i64) -> Fraction {
        Fraction::new(n, 1)
    }
}

fn main() {
    let half = Fraction::new(1, 2);
    let third = Fraction::new(1, 3);
    let sixth = Fraction::new(1, 6);

    println!("{half} + {third} + {sixth} = {}", half + third + sixth);
    println!("{half} * {third} = {}", half * third);
    println!("6/-8 in lowest terms: {}", Fraction::new(6, -8));

    let three: Fraction = 3.into();
    println!(
        "3 * 1/6 = {}, and 3 == 6/2 is {}",
        three * sixth,
        three == Fraction::new(6, 2)
    );
    println!("{:?}", Fraction::new(10, 4));
}
text
1/2 + 1/3 + 1/6 = 1
1/2 * 1/3 = 1/6
6/-8 in lowest terms: -3/4
3 * 1/6 = 1/2, and 3 == 6/2 is true
Fraction { num: 5, den: 2 }

Some details:

  • Display has one required method, fmt, which writes to a Formatter with the write! macro. Once Display is implemented you also get .to_string() for free, through a blanket implementation in the standard library: it implements ToString for every type that implements Display.
  • Add has an associated type, Output, saying what type a + b produces. Most often it is Self, but adding two instants in time might reasonably produce something else. Associated types are how a trait lets each implementation fix a related type once; Iterator's Item in the next lesson is the most famous example.
  • Implementing From<i64> for Fraction gives callers both Fraction::from(3) and let x: Fraction = 3.into();, again through a blanket implementation (of Into).
  • Equality comes from #[derive(PartialEq, Eq)]. Because new always reduces, comparing fields is correct: 3 and 6/2 are both stored as 3/1. Deriving is only right when field-by-field comparison matches the meaning of your type; when it doesn't, implement PartialEq by hand.

The traits you will implement or derive most often:

TraitGives youUsually
Debug{:?}derive on almost every type
Display{}, .to_string()implement for user-facing types
Clone, Copy.clone(), implicit copiesderive (Copy only for small plain data)
PartialEq, Eq==, !=derive
PartialOrd, Ord<, >, sortingderive or implement
Hashuse as a HashMap keyderive together with Eq
DefaultT::default()derive or implement
From, TryFromconversions, .into(), ? on errorsimplement
Add, Mul, Neg, Index, ...operatorsimplement for numeric-like types

Two related rules keep this sane. The orphan rule says you may implement a trait for a type only if the trait or the type is defined in your own crate: you can implement Display for Fraction, or your own trait for i64, but not Display for the standard library's vector type (the compiler reports error E0117). This guarantees that two libraries can never provide conflicting implementations. The usual workaround is a newtype around the foreign type. And PartialEq/PartialOrd exist separately from Eq/Ord because floating-point numbers have NaN, which is not equal to itself; that is why you cannot directly sort a vector of f64 with .sort(), and use .sort_by(|a, b| a.total_cmp(b)) instead.

Worked examplesH

Generic types

Structs and enums can take type parameters too. You have used several already: Option<T>, Result<T, E>, and vectors. Here is a closed interval that works for any type with an order:

rust
use std::fmt::Display;

/// A closed interval [lo, hi] of any ordered type.
#[derive(Debug, Clone, Copy)]
struct Interval<T> {
    lo: T,
    hi: T,
}

impl<T: PartialOrd + Copy> Interval<T> {
    fn new(a: T, b: T) -> Self {
        if a <= b {
            Interval { lo: a, hi: b }
        } else {
            Interval { lo: b, hi: a }
        }
    }

    fn contains(&self, x: T) -> bool {
        self.lo <= x && x <= self.hi
    }

    fn overlap(&self, other: &Interval<T>) -> Option<Interval<T>> {
        let lo = larger(self.lo, other.lo);
        let hi = smaller(self.hi, other.hi);
        (lo <= hi).then_some(Interval { lo, hi })
    }
}

fn larger<T: PartialOrd>(a: T, b: T) -> T {
    if a >= b { a } else { b }
}

fn smaller<T: PartialOrd>(a: T, b: T) -> T {
    if a <= b { a } else { b }
}

// Methods that exist only when T can also be displayed.
impl<T: Display> Interval<T> {
    fn show(&self) -> String {
        format!("[{}, {}]", self.lo, self.hi)
    }
}

// A generic function with a `where` clause.
fn count_inside<T>(range: &Interval<T>, values: &[T]) -> usize
where
    T: PartialOrd + Copy,
{
    let mut n = 0;
    for &v in values {
        if range.contains(v) {
            n += 1;
        }
    }
    n
}

fn main() {
    let shift = Interval::new(9, 17); // hours, i32
    let meeting = Interval::new(16, 19);
    match shift.overlap(&meeting) {
        Some(both) => println!("overlap {}", both.show()),
        None => println!("no overlap"),
    }

    let comfortable = Interval::new(18.5, 24.0); // degrees, f64
    println!(
        "{}: {} of 5 readings",
        comfortable.show(),
        count_inside(&comfortable, &[17.0, 19.5, 22.1, 25.3, 23.9])
    );

    let first_half = Interval::new('a', 'm'); // characters
    println!("'q' in {}? {}", first_half.show(), first_half.contains('q'));

    let dates = Interval::new((2026, 3, 1), (2026, 5, 31)); // tuples compare field by field
    println!(
        "{:?} in spring term? {}",
        (2026, 4, 15),
        dates.contains((2026, 4, 15))
    );
}
text
overlap [16, 17]
[18.5, 24]: 3 of 5 readings
'q' in [a, m]? false
(2026, 4, 15) in spring term? true

impl<T: PartialOrd + Copy> Interval<T> reads "for every T that can be compared and copied, intervals of T have these methods". A second impl block adds show only for types that implement Display; an interval of a type without Display simply wouldn't have a show method. The same struct is then used with integers, floats, characters and tuples of three integers (tuples compare element by element, so (year, month, day) orders dates correctly). Notice, too, that the float 24.0 is displayed as 24: that is how Display formats a float with no fractional part.

How generics are compiled

The compiler handles generic code by monomorphisation: for each concrete type used, it generates a separate copy of the function with the type filled in. Interval::contains becomes four functions here (for i32, f64, char and the tuple), each compiled and optimised as if you had written it by hand. The cost is paid at compile time and in binary size, never at run time. This is why generic Rust code, including all the iterator adaptors of the next lesson, is as fast as the loops you would otherwise write. It is also one reason Rust builds can be slow: heavily generic code means more code for LLVM to optimise.

DefinitionsH

Trait objects and dynamic dispatch

Generics require the compiler to know the concrete type. Sometimes it can't: you want a list of notification channels, some SMS, some email, chosen from a configuration file at run time. A Vec<T> holds one type, but you can store pointers to values of different types that all implement one trait.

Definition— trait object

A trait object, written dyn Trait, is a value of some unknown type that implements Trait. Because its size is unknown, it always sits behind a pointer: &dyn Trait, Box<dyn Trait> (an owned pointer to the heap) or similar. Method calls on it use dynamic dispatch: the pointer carries a second pointer to a vtable, a table of the concrete type's method addresses, and the call goes through that table at run time.

rust
use std::mem::size_of;

trait Notifier {
    fn channel(&self) -> &str;
    fn send(&self, message: &str) -> String;
}

struct Sms {
    number: String,
}

struct Email {
    address: String,
}

struct Pager;

impl Notifier for Sms {
    fn channel(&self) -> &str {
        "SMS"
    }
    fn send(&self, message: &str) -> String {
        let short: String = message.chars().take(20).collect();
        format!("to {}: {short}", self.number)
    }
}

impl Notifier for Email {
    fn channel(&self) -> &str {
        "email"
    }
    fn send(&self, message: &str) -> String {
        format!("to {}: {message}", self.address)
    }
}

impl Notifier for Pager {
    fn channel(&self) -> &str {
        "pager"
    }
    fn send(&self, _message: &str) -> String {
        String::from("beep")
    }
}

// A trait object: any type that implements Notifier, chosen at run time.
fn alert_all(targets: &[Box<dyn Notifier>], message: &str) {
    for t in targets {
        println!("[{}] {}", t.channel(), t.send(message));
    }
}

fn main() {
    let on_call: Vec<Box<dyn Notifier>> = vec![
        Box::new(Sms {
            number: String::from("+81 90-xxxx-0042"),
        }),
        Box::new(Email {
            address: String::from("ops@example.org"),
        }),
        Box::new(Pager),
    ];
    alert_all(&on_call, "Disk usage above 90% on db-2");

    println!(
        "&Sms: {} bytes, &dyn Notifier: {} bytes",
        size_of::<&Sms>(),
        size_of::<&dyn Notifier>()
    );
}
text
[SMS] to +81 90-xxxx-0042: Disk usage above 90%
[email] to ops@example.org: Disk usage above 90% on db-2
[pager] beep
&Sms: 8 bytes, &dyn Notifier: 16 bytes

Box::new(Sms { ... }) allocates the value on the heap; the vector's element type Box<dyn Notifier> forgets which concrete type is inside and keeps only the vtable. The last line shows the cost on this 64-bit machine: a reference to a known type is one pointer (8 bytes), while a reference to a trait object is a fat pointer, a data pointer plus a vtable pointer (16 bytes). Each call through it is an indirect jump, which also prevents the optimiser from inlining the method.

Not every trait can be used as a trait object. A trait is dyn compatible (older documentation says "object safe") only if every method can be called without knowing the concrete type: no generic methods, no methods that return Self by value, and a few similar rules. The compiler tells you precisely which method is the problem if you try.

ExplanationH

Static or dynamic dispatch: how professionals choose

Rust makes you choose explicitly between impl Trait/generics (static dispatch) and dyn Trait (dynamic dispatch). In practice:

  • Default to generics for functions that take "something that can do X": parsers that accept any reader, functions over any iterator, algorithms over any ordered type. You get inlining and specialised code.
  • Use dyn Trait for heterogeneous collections (plugins, UI widgets, notification channels, middleware chains) and when the concrete type is decided at run time.
  • Use dyn Trait to tame compile times and binary size when a large generic function would be duplicated for many types and the indirect call is negligible beside the work done.
  • Consider an enum instead of either. If the set of variants is closed and known (three payment methods, four notification channels that you own), an enum with a match is often simpler, faster and checked for exhaustiveness. Traits shine when the set is open: other crates or future code will add implementations.

impl Trait also works in return position: fn evens() -> impl Iterator<Item = u32> promises "some type that implements this trait, which I'm not naming". The caller can use only the trait's methods, and the concrete type stays a private detail you are free to change. Since edition 2024, such a return type captures all the function's generic parameters and lifetimes by default, which removed a long-standing source of confusing errors.

Finally, some vocabulary you will see in documentation: a supertrait is a trait that requires another (trait Shape: Display means every shape must also be displayable); a marker trait has no methods and only records a property (Copy, Send, Sync); and since Rust 1.86, a trait object can be upcast to a trait object of one of its supertraits.

Common misconceptionsH

Common misconceptions

Misconception

"Traits are Rust's version of inheritance." Traits describe behaviour that types share; they do not let one struct inherit another's fields or method bodies. Default methods are the closest thing, and they can only build on the trait's own methods. Rust composes: a struct contains other structs and implements whichever traits make sense.

Misconception

"Generic code is slower because it handles many types." The opposite is usually true. Monomorphisation produces specialised code for each type, which the optimiser can inline. The run-time cost appears only with dyn Trait, and even then it is one indirect call per method.

Misconception

"impl Trait and dyn Trait are interchangeable spellings." impl Trait is one concrete type chosen at compile time (static dispatch); dyn Trait is any implementing type, chosen at run time, behind a pointer (dynamic dispatch). A function returning impl Trait cannot return a Sms on one path and an Email on another; returning Box<dyn Notifier> can.

Misconception

"I can implement any trait for any type." The orphan rule forbids implementing a foreign trait for a foreign type. Wrap the foreign type in your own newtype, or define your own trait.

Exercises

Exercises

1. Traits and generics

Warm-upComputational

What does this program print?

trait Greet {
    fn name(&self) -> String;
    fn hello(&self) -> String {
        format!("Hello, {}", self.name())
    }
}

struct A;
struct B;

impl Greet for A {
    fn name(&self) -> String { "Ana".into() }
}

impl Greet for B {
    fn name(&self) -> String { "Bo".into() }
    fn hello(&self) -> String { format!("Hi {}!", self.name()) }
}

fn main() {
    println!("{} / {}", A.hello(), B.hello());
}

2. Traits and generics

CoreComputational

Using the lesson's Fraction type, what do these three lines print? Write them separated by spaces.

println!("{}", Fraction::new(2, 4) + Fraction::new(1, 4));
println!("{}", Fraction::new(-3, -9));
println!("{}", Fraction::new(4, 2) * Fraction::new(1, 3));

3. Traits and generics

CoreComputational

Given

fn larger<T: PartialOrd>(a: T, b: T) -> T {
    if a >= b { a } else { b }
}

what do larger("pear", "apple") and larger("Zebra", "apple") return? Write the two words separated by a space.

4. Traits and generics

CoreHuman

On a 64-bit machine, how many bytes does a &dyn Notifier take?

5. Traits and generics

StretchHuman

In which situations is dyn Trait (dynamic dispatch) a better fit than generics? Choose all that apply.

Choose all that apply

6. Traits and generics

CoreHuman

In your own crate, which of these implementations is not allowed?

Choose one

Further reading and resources