FerrousPath

Level 2 · Practitioner· Lesson 1 of 8 · 20 min

Generics

Writing code once for many types, how monomorphization makes it free at runtime, and const generics.

The problem generics solve

fn largest_i32(xs: &[i32]) -> i32 {
    let mut max = xs[0];
    for &x in xs {
        if x > max { max = x; }
    }
    max
}

fn main() {
    println!("{}", largest_i32(&[3, 9, 2]));
}

To support f64 or char you would copy the function and change one word. Generics let you write it once:

fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T {
    let mut max = xs[0];
    for &x in xs {
        if x > max { max = x; }
    }
    max
}

fn main() {
    println!("{}", largest(&[3, 9, 2]));
    println!("{}", largest(&[1.5, 0.2]));
    println!("{}", largest(&['x', 'b']));
}

<T: PartialOrd + Copy> declares a type parameter with trait bounds: T can be any type that supports ordering comparison and bitwise copy. Remove the bounds and the compiler refuses — a generic function body is checked once, using only what the bounds promise. This is unlike C++ templates, which are checked at each use; in Rust, if the generic function compiles, it compiles for every T that satisfies the bounds.

Generic structs and enums

#[derive(Debug)]
struct Point<T> {
    x: T,
    y: T,
}

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

// Methods only for particular type arguments:
impl Point<f64> {
    fn distance_from_origin(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}

fn main() {
    let a = Point::new(1, 2);
    let b = Point::new(3.0, 4.0);
    println!("{a:?} {b:?} {}", b.distance_from_origin());
    // a.distance_from_origin(); // ❌ no such method on Point<i32>
}

You already use generic enums constantly: Option<T> and Result<T, E> are defined in the standard library exactly the way you would define them yourself.

where clauses

When bounds get long, move them after the signature:

use std::fmt::Debug;
use std::collections::HashMap;
use std::hash::Hash;

fn count<T, I>(items: I) -> HashMap<T, usize>
where
    T: Eq + Hash,
    I: IntoIterator<Item = T>,
{
    let mut map = HashMap::new();
    for item in items {
        *map.entry(item).or_insert(0) += 1;
    }
    map
}

fn show<T>(label: &str, value: T)
where
    T: Debug,
{
    println!("{label}: {value:?}");
}

fn main() {
    show("letters", count("mississippi".chars()).get(&'s'));
    show("numbers", count(vec![1, 1, 2]).len());
}

Monomorphization: zero-cost generics

When you call largest with i32 and with f64, the compiler generates two functions, as if you had written largest_i32 and largest_f64 by hand. This is monomorphization.

  • Benefit: no runtime dispatch, no boxing, full inlining. Generic code is as fast as hand-specialised code.
  • Cost: longer compile times and bigger binaries when a generic function is instantiated with many types.

The alternative — one compiled copy that works through a pointer and a table of functions — is dynamic dispatch with dyn Trait, covered in Level 3.

Const generics

Types can also be parameterised by constant values:

#[derive(Debug)]
struct Matrix<const R: usize, const C: usize> {
    cells: [[f64; C]; R],
}

impl<const R: usize, const C: usize> Matrix<R, C> {
    fn zero() -> Self {
        Matrix { cells: [[0.0; C]; R] }
    }

    fn transpose(&self) -> Matrix<C, R> {
        let mut out = Matrix::<C, R>::zero();
        for r in 0..R {
            for c in 0..C {
                out.cells[c][r] = self.cells[r][c];
            }
        }
        out
    }
}

fn main() {
    let mut m = Matrix::<2, 3>::zero();
    m.cells[0][2] = 7.0;
    let t = m.transpose(); // type is Matrix<3, 2>
    println!("{:?}", t.cells);
}

The dimensions are checked at compile time and cost nothing at runtime. Arrays themselves, [T; N], are the built-in example.

Exercises

  1. Write a generic struct Pair<T> with a method fn largest(&self) -> &T available only when T: PartialOrd.
  2. Write fn swap_pair<A, B>(p: (A, B)) -> (B, A).
  3. Write a Stack<T> wrapper around Vec<T> with push, pop -> Option<T>, peek -> Option<&T>, and is_empty.
Solution to 1
struct Pair<T> { a: T, b: T }

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

fn main() {
    let p = Pair { a: "apple", b: "pear" };
    println!("{}", p.largest());
}

Returning &T avoids needing Copy or Clone.

Check your understanding

Pick an answer to see the explanation.

  1. 1.What is monomorphization?

  2. 2.Why does fn largest<T>(xs: &[T]) -> &T fail to compile if the body uses >?

  3. 3.What is N in struct Buf<const N: usize>?

Key terms in this lesson

Finished the lesson and the exercises?