Generics in Rust

With generics, you write code once for many types: fn largest<T: PartialOrd>(items: &[T]) -> &T. T is a type parameter, a blank for a type that is filled in…

Rusdi wants to find the receipt with the biggest amount today. Tomorrow he wants the menu name that comes last alphabetically, then the review rating with the most stars. If you write one function for each, you get three functions with exactly the same body, and only the type differs: whole numbers, text and decimals.

With generics, one is enough. One function or struct (covered below) works for many types at once. The type is written as a blank, usually named T, and the compiler fills it in from the type of the values sent when the function is called. Think of the SOP card (a card with a work rule) on the wall of Rusdi's Pancake Stall: "From one pile, take the biggest." The card is written once and works for any pile. In its corner there is one condition: "the things must be comparable." In code, the card is a generic function, the kind of thing in the pile is T, and the condition in the card's corner is a trait bound.

One function for many types

The function largest below finds the biggest item in a list. main uses it for three lists of three different types:

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

fn main() {
    let orders: Vec<u32> = vec![102, 70, 38, 45];
    let menu = vec!["egg pancake", "sweet pancake", "iced tea"];
    let rating: Vec<f64> = vec![4.5, 4.8, 3.9];
    println!("{}", largest(&orders));
    println!("{}", largest(&menu));
    println!("{}", largest(&rating));
}

The output:

102
sweet pancake
4.8

This table shows the steps of largest(&menu), one row per round. Text is compared letter by letter like dictionary order, so "sweet pancake" is bigger than "egg pancake" (s comes after e), and bigger than "iced tea" too (s comes after i).

item item > result? result afterwards
"egg pancake" false (equal) "egg pancake"
"sweet pancake" true "sweet pancake"
"iced tea" false "sweet pancake"

Trait bounds: conditions on T

A trait is the name of one ability a type has. PartialOrd means "can be compared with < and >", and Display means "can be printed with {}". u32, &str and f64 have both. Making your own trait comes in the Traits lesson.

Now delete the condition, leaving fn largest<T>(items: &[T]) -> &T. Say the function is only called with a Vec<u32>, numbers that can clearly be compared. Before you look at the result, guess: does this <T> with no condition compile?

error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/main.rs:4:17
  |
4 |         if item > result {
  |            ---- ^ ------ &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> &T {
  |             ++++++++++++++++++++++

The code is refused, even though the only caller uses u32. The reason: Rust checks a generic function's body on its own, without looking at the code that calls it. T may be any type that meets its conditions. With no condition, T could be a type that can't be compared. The help: writes the full name, std::cmp::PartialOrd, but plain T: PartialOrd is enough.

A condition is also a limit: inside the function, T can only be used as its conditions allow. This function prints the result of largest, but the only condition on its T is that it can be compared:

fn announce<T: PartialOrd>(items: &[T]) {
    println!("Largest: {}", largest(items));
}
error[E0277]: `T` doesn't implement `std::fmt::Display`
  --> src/main.rs:12:29
   |
12 |     println!("Largest: {}", largest(items));
   |                        --   ^^^^^^^^^^^^^^ `T` cannot be formatted with the default formatter

Printing with {} needs the ability Display, and Display isn't in the conditions on T. When T needs two abilities, join them with +. When the conditions get long, move them into a where part after the parameter list. The two functions below have the same conditions, written in two ways:

use std::fmt::Display;

fn announce<T: PartialOrd + Display>(items: &[T]) {
    println!("Largest: {}", largest(items));
}

fn announce_again<T>(items: &[T])
where
    T: PartialOrd + Display,
{
    println!("Largest: {}", largest(items));
}

announce(&orders) prints Largest: 102, and announce(&menu) prints Largest: sweet pancake. Display needs use std::fmt::Display; at the top of the file.

Generic structs: Container

A struct groups several named values into one new type, and it is covered fully in the next lesson. Structs can be generic too, like Container below:

struct Container<T> {
    contents: T,
}

impl<T> Container<T> {
    fn view(&self) -> &T {
        &self.contents
    }
}

fn main() {
    let parcel = Container { contents: "egg pancake" };
    let price: Container<u32> = Container { contents: 38 };
    println!("{}", parcel.view());
    println!("{}", price.view());
}

The output is egg pancake, then 38.

Monomorphization: generics at no cost

At compile time, Rust makes a concrete copy of a generic function for each type that is actually used: a copy with T replaced by that type. From the largest program above, the compiler writes three functions: largest::<u32>, largest::<&str> and largest::<f64>. Each is exactly like a function you wrote yourself for that type. This is called monomorphization. Because it all happens at compile time, generics in Rust are zero-cost (no extra cost while the program runs). When the program runs there is no extra type check or lookup table, so the function is as fast as one written by hand for each type. The price is paid at compile time, and in a slightly bigger binary (the program file the compile produces).

⚠️ Conditions that are missing, mistyped, or too strict

TL;DR: With generics, you write code once for many types: fn largest<T: PartialOrd>(items: &[T]) -> &T. T is a type parameter, a blank for a type that is filled in from the argument (u32, &str, f64). T: PartialOrd is a trait bound: an ability T must have, here being comparable with < and >. Rust checks a generic function's body without looking at the code that calls it, so without the trait bound, > is refused (E0369), and printing a T without Display (the ability to be printed with {}) is refused (E0277). Several conditions are joined with + (T: Display + Clone) or written in a where part. Structs (types that group several named values) can be generic too, struct Container<T> { contents: T }, with methods in impl<T> Container<T>. At compile time, monomorphization makes a concrete copy of the function per type used, so generics add no cost while the program runs.

⚡ One function, many types

Write:

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

Meaning: The function largest finds the biggest item in a list, for any type. The type parameter list <T: PartialOrd> goes right after the function name: T is a blank for one type, and PartialOrd is its condition, being comparable with >. items: &[T] is a slice (a borrow of a list's items) of T. When the function is called, T is filled in from the argument: u32 for the list of numbers orders, &str for the list of names menu, f64 for the list rating.

⚡ A condition on T

Guess first: the condition PartialOrd is deleted, leaving fn largest<T>, though the function is only called with a Vec<u32>. Does it compile?

No. Rust checks a generic function's body on its own, without looking at its callers. With no condition, T could be a type that can't be compared, so item > result is refused with error E0369.

Meaning: T: PartialOrd is a trait bound, an ability T must have. A trait is the name of one ability, such as PartialOrd (can be compared) and Display (can be printed with {}). Two conditions are joined with +: T: PartialOrd + Display.

⚡ Generics at no cost

Meaning: At compile time, Rust makes a concrete copy per type used, that is, a copy of largest with T replaced by that type: largest::<u32>, largest::<&str> and largest::<f64>. This is called monomorphization. Because the copies are made at compile time, there is no extra cost when the program runs.

What you will learn