Skip to content
RustLearn

Module 11 — Generics

Goal

Write code once for many types with zero runtime cost. Monomorphization, generic structs and functions, and trait bounds as requirements.

Start here — what this module is really about

You have written the same function twice with a different type in it. Everyone has. Generics are how you stop.

rust
fn largest_i32(list: &[i32]) -> &i32 { }
fn largest_char(list: &[char]) -> &char { }

These differ only in a type name. A generic lets you leave that name as a blank to be filled in later:

rust
fn largest<T>(list: &[T]) -> &T { }

Read <T> as "for some type, which I will call T". It is not a special type; it is a placeholder, and the caller decides what goes there.

There is one immediate complication and one big payoff.

The complication: inside that function you cannot do just anything with a T. If you write a > b, the compiler asks: how do you know T can be compared? Some types cannot. So you must state your requirements, and that is what a trait bound is — T: PartialOrd means "whatever T is, it must support comparison". Bounds are how a generic function's contract is written down, and the compiler checks callers against it.

The payoff: it costs nothing. When you call largest with i32, the compiler generates a copy of the function specialised for i32, as if you had written it by hand. That process is called monomorphization, and it means Rust's generics have no runtime lookup, no boxing, and no speed penalty — unlike the generics of several other languages.

You have been using generics since module 08 without noticing: Option<T>, Result<T, E> and Vec<T> are all generic types.

The one sentence to remember: a generic is a blank for a type, a trait bound says what may fill it, and the compiler prints a specialised copy for each type you actually use.

Learning objectives

  • Write generic functions, structs, enums, and methods
  • Apply trait bounds, including where clauses
  • Understand monomorphization and why generics are zero-cost
  • Use const generics and generic associated types at a basic level
  • Recognize when generics are the wrong tool

11.1 The duplication generics remove

rust
fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];
    for item in list { if item > largest { largest = item; } }
    largest
}

fn largest_char(list: &[char]) -> &char { /* identical body */ }

Generic version:

rust
fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest { largest = item; }
    }
    largest
}

fn main() {
    println!("{}", largest(&[34, 50, 25, 100, 65]));
    println!("{}", largest(&['y', 'm', 'a', 'q']));
    println!("{}", largest(&[1.2, 9.8, 3.3]));
}

Read <T: PartialOrd> as: "for any type T that can be compared with <". Without the bound you get:

error[E0369]: binary operation `>` cannot be applied to type `&T`
help: consider restricting type parameter `T`: `T: std::cmp::PartialOrd`

The compiler literally tells you which bound to add. This is the normal workflow: write the generic, let the error name the bound, add it.


Analogy — the blank in the form

Writing largest_i32, largest_f64 and largest_char is printing three near-identical forms and re-typing the boilerplate each time. A generic is the same form with the type left as a blank to be filled in on use. You are not writing code that decides at runtime — you are writing a template a machine will print in whatever type is asked for.

11.2 Generic structs and enums

rust
struct Point<T> { x: T, y: T }

let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
// let mixed = Point { x: 5, y: 4.0 };   // ❌ both fields must be the same T

struct Pair<T, U> { first: T, second: U }
let mixed = Pair { first: 5, second: 4.0 };   // ✅

Standard library examples you already use:

rust
enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Err(E) }
struct Vec<T> { /* ... */ }
struct HashMap<K, V> { /* ... */ }

Generic methods

rust
impl<T> Point<T> {
    fn x(&self) -> &T { &self.x }
}

// methods only available for a specific concrete type
impl Point<f64> {
    fn distance_from_origin(&self) -> f64 {
        (self.x.powi(2) + self.y.powi(2)).sqrt()
    }
}

// methods available only when T satisfies a bound
impl<T: std::fmt::Display + PartialOrd> Point<T> {
    fn cmp_display(&self) {
        if self.x >= self.y { println!("largest x = {}", self.x); }
        else { println!("largest y = {}", self.y); }
    }
}

Note impl<T> declares the parameter; Point<T> uses it. Forgetting the first <T> is a common early error.

Methods with their own type parameters

rust
struct Point<X1, Y1> { x: X1, y: Y1 }

impl<X1, Y1> Point<X1, Y1> {
    fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> {
        Point { x: self.x, y: other.y }
    }
}

X1, Y1 come from the struct; X2, Y2 are local to the method.

11.3 Trait bounds

Three equivalent syntaxes:

rust
// 1. inline
fn notify<T: Summary>(item: &T) {}

// 2. impl Trait (argument position) — concise, but no way to name T
fn notify(item: &impl Summary) {}

// 3. where clause — best when bounds get long
fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: std::fmt::Display + Clone,
    U: Clone + std::fmt::Debug,
{
    0
}

Use impl Trait for single simple bounds; use where as soon as you have two type parameters or two bounds each — it keeps the signature readable.

Multiple bounds combine with +:

rust
fn print_all<T: std::fmt::Display + Clone>(items: &[T]) {}

Return position impl Trait

rust
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

This returns "some concrete type implementing Fn" without naming it (closure types have no nameable name). Restriction: all return paths must yield the same concrete type. If you need to return different types, use Box<dyn Trait> (module 12).

Conditional implementations

rust
use std::fmt::Display;

struct Pair<T> { x: T, y: T }

impl<T> Pair<T> {
    fn new(x: T, y: T) -> Self { Self { x, y } }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn cmp_display(&self) {
        if self.x >= self.y { println!("largest is x = {}", self.x); }
        else { println!("largest is y = {}", self.y); }
    }
}

Pair<T>::new exists for every T; cmp_display only exists when T: Display + PartialOrd. This is how the standard library gives Vec<T> a sort method only when T: Ord.

Blanket implementations

rust
impl<T: Display> ToString for T {
    // ...
}

The standard library implements ToString for every type that implements Display. That's why 42.to_string() works without anyone writing that impl for integers.


Trait bounds — three ways to write the same thing

The moment you do anything with a generic value, you need a bound. Here is the same requirement in the three syntaxes you will meet:

rust
// 1. Inline — fine for one or two bounds
fn largest<T: PartialOrd>(list: &[T]) -> &T { }

// 2. where clause — much easier to read once there are several
fn process<T, U>(a: T, b: U) -> String
where
    T: Display + Clone,
    U: Debug,
{ }

// 3. impl Trait in argument position — shorthand when you never name the type
fn notify(item: &impl Summary) { }

How to read a bound: T: Display + Clone means "T must be printable and duplicable". Each name after the colon is a capability the type must have; + combines them.

The practical workflow, which is worth adopting deliberately: write the generic function with no bounds, compile, and let the compiler tell you what is missing. You will get something like

text
error[E0369]: binary operation `>` cannot be applied to type `T`
help: consider restricting type parameter `T`: `T: PartialOrd`

That help: line is the bound you need, spelled correctly. This is one of the places where treating the compiler as a collaborator rather than a gatekeeper genuinely speeds you up.

Analogy — the job advert, not the person

A trait bound is the requirements line in a job advert: must be comparable, must be printable. You are not naming a candidate, you are naming what the candidate must be able to do — and the compiler refuses any applicant who cannot do all of it. This is why a generic function's errors read as 'this type doesn't meet the requirements' rather than as a mystery further in.

11.4 Monomorphization: why this is free

At compile time, Rust generates a separate copy of the code for each concrete type used:

rust
let integer = Some(5);
let float = Some(5.0);

becomes, roughly:

rust
enum Option_i32 { Some(i32), None }
enum Option_f64 { Some(f64), None }

Consequences:

  • Zero runtime cost. No vtables, no boxing, no type checks. Generic code is as fast as hand-specialized code — often faster, since each copy is optimized for its type.
  • Larger binaries and slower compiles. Every instantiation is compiled separately. This is the real cost of generics in Rust, and it's why heavily generic crates (like serde or diesel) compile slowly.

TS ↔ Rust: TypeScript generics are erased — one implementation, checked at compile time, no runtime specialization. Rust generics are expanded, like C++ templates, but with bounds checked at definition time rather than at instantiation, so error messages point at the generic code rather than dumping a page of template noise.


Monomorphization, made concrete

This is the bit that makes Rust generics different from Java's or Python's duck typing, so it is worth seeing literally.

You write:

rust
fn largest<T: PartialOrd>(list: &[T]) -> &T { }

largest(&[1, 5, 3]);           // called with i32
largest(&['a', 'z', 'm']);     // called with char

The compiler generates, roughly:

rust
fn largest_i32(list: &[i32]) -> &i32 { }
fn largest_char(list: &[char]) -> &char { }

...and rewrites your two call sites to call those. By the time your program runs, there are no generics left. There is no type information carried at runtime, no lookup table, no boxing of values.

The consequences, both directions:

  • Speed: a generic function is exactly as fast as the hand-written specialised one. This is what "zero-cost abstraction" means in practice.
  • Compile time and binary size: each concrete type you use generates another copy. This is a real cost — heavily generic crates compile slowly and produce larger binaries. It is the trade Rust chose, and §11.6 covers when to choose otherwise (trait objects, module 12).

Analogy — printed on demand

Monomorphization is the print shop: you supplied one master template, and at build time the compiler runs off a separate concrete copy for each type you actually used. At runtime there are no generics left to interpret and nothing to look up — the abstraction cost you compile time and precisely zero nanoseconds.

11.5 Const generics

Generic over values, not just types:

rust
struct Buffer<const N: usize> {
    data: [u8; N],
}

impl<const N: usize> Buffer<N> {
    fn new() -> Self { Buffer { data: [0; N] } }
    fn len(&self) -> usize { N }
}

fn sum_array<const N: usize>(arr: [i32; N]) -> i32 {
    arr.iter().sum()
}

fn main() {
    let b: Buffer<64> = Buffer::new();
    println!("{}", b.len());
    println!("{}", sum_array([1, 2, 3]));       // N inferred as 3
    println!("{}", sum_array([1, 2, 3, 4, 5])); // N inferred as 5
}

This is how the standard library implements traits for all array sizes ([T; N]) — before const generics, Debug was implemented for arrays up to length 32 only, by macro.

11.6 When generics are the wrong tool

Generics are for code that is genuinely identical across types. They're the wrong choice when:

  • You need heterogeneous collections. Vec<T> holds one T. If you need mixed types at runtime, use an enum or Vec<Box<dyn Trait>>.
  • The type is chosen at runtime. Monomorphization happens at compile time; if the type comes from a config file, you need dynamic dispatch.
  • The abstraction is speculative. Two implementations is the usual threshold. One concrete type with a TODO beats a generic parameter nobody else will ever instantiate.
  • Compile time matters more than the last 2%. A dyn Trait boundary can cut compile times dramatically in a large crate.

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
genericCode written once that works for many types, with the type left as a parameter.
type parameterThe placeholder itself, conventionally T, U, K, V.
trait boundA requirement on a type parameter: T: Display means "T must be printable".
where clauseAn alternative place to write bounds, for readability.
monomorphizationGenerating a specialised copy of generic code for each concrete type used.
impl TraitShorthand for "some type implementing this trait", in an argument or return position.
const genericA generic over a value rather than a type, e.g. array length [T; N].
turbofish ::<>Explicitly naming a generic type at a call site: parse::<i32>().

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[E0369]: binary operation cannot be applied to type TYou compared or added generic values without requiring that ability.Add the bound the help: line suggests, usually PartialOrd or Add.
error[E0507]: cannot move out of indexYou returned T by value from a slice you only borrowed.Return &T, or add a T: Copy / T: Clone bound if you truly need ownership.
error[E0282]: type annotations neededThe compiler cannot infer what the generic should be.Say it explicitly: let n = "5".parse::<i32>()?; or annotate the binding.
error[E0277]: the trait bound is not satisfiedA caller passed a type lacking a required capability.Either implement the missing trait for that type, or relax the bound.
Compiles slowly with many generic typesMonomorphization is generating many copies.Normal. If it becomes a problem, consider a trait object (module 12) at the boundary.

Now make it stick: work through the drills for this module, then carry on to Module 12 — Traits & Trait Objects.