TExcelTAD
Home › Rust › Rust Generics

Rust Generics

Generics let you write one piece of code that works with many types. Instead of writing largest_i32, largest_f64 and largest_char, you write a single largest<T> and let the compiler fill in the type. You have already used generic types without noticing: Vec<T>, Option<T> and HashMap<K, V> are all generic.

Generic functions

A type parameter is declared in angle brackets after the function name. By convention it is a short capital letter such as T.

rust · try it yourself
fn first_and_last<T: Copy>(items: &[T]) -> (T, T) {
    (items[0], items[items.len() - 1])
}

fn main() {
    let scores = [72, 85, 91, 64];
    let letters = ['r', 'u', 's', 't'];

    println!("{:?}", first_and_last(&scores));
    println!("{:?}", first_and_last(&letters));
}
(72, 64)
('r', 't')

The T: Copy part is a trait bound. It says "T can be any type, as long as it implements Copy". Without it the compiler would refuse to copy items[0] out of the slice, because not every type can be copied.

Why trait bounds are needed

The compiler checks generic code once, for every possible T. If your function compares values with >, it must be told that T supports comparison — that is the PartialOrd trait.

rust
fn largest<T>(items: &[T]) -> &T {
    let mut best = &items[0];
    for item in items {
        if item > best {   // error: `T` might not support `>`
            best = item;
        }
    }
    best
}
error[E0369]: binary operation `>` cannot be applied to type `&T`
help: consider restricting type parameter `T` with trait `PartialOrd`

Adding the bound fixes it:

rust · try it yourself
fn largest<T: PartialOrd>(items: &[T]) -> &T {
    let mut best = &items[0];
    for item in items {
        if item > best {
            best = item;
        }
    }
    best
}

fn main() {
    let temps = [18.5, 22.1, 19.8];
    let words = ["pear", "apple", "zucchini", "kiwi"];

    println!("Warmest: {}", largest(&temps));
    println!("Last alphabetically: {}", largest(&words));
}
Warmest: 22.1
Last alphabetically: zucchini

You can combine several bounds with +, for example T: PartialOrd + std::fmt::Display. When the list gets long, move it into a where clause:

rust
fn summary<T, U>(a: T, b: U) -> String
where
    T: std::fmt::Display,
    U: std::fmt::Debug,
{
    format!("{} / {:?}", a, b)
}

Generic structs

Structs can be generic too. Here Pair<T> holds two values of the same type, while Labeled<T> attaches a text label to a value of any type.

rust · try it yourself
#[derive(Debug)]
struct Pair<T> {
    left: T,
    right: T,
}

impl<T: PartialOrd + Copy> Pair<T> {
    fn bigger(&self) -> T {
        if self.left > self.right { self.left } else { self.right }
    }
}

struct Labeled<T> {
    label: String,
    value: T,
}

fn main() {
    let ints = Pair { left: 7, right: 12 };
    let floats = Pair { left: 2.5, right: 1.5 };

    println!("{:?} -> {}", ints, ints.bigger());
    println!("{:?} -> {}", floats, floats.bigger());

    let tagged = Labeled { label: String::from("port"), value: 8080 };
    let flag = Labeled { label: String::from("debug"), value: true };
    println!("{} = {}", tagged.label, tagged.value);
    println!("{} = {}", flag.label, flag.value);
}
Pair { left: 7, right: 12 } -> 12
Pair { left: 2.5, right: 1.5 } -> 2.5
port = 8080
debug = true

Notice impl<T: PartialOrd + Copy> Pair<T>: the bigger method only exists for pairs whose type can be compared and copied. A Pair<String> could still be created, it just would not have bigger.

Generic enums

The two most important enums in Rust are generic:

Enum Definition Used for
Option<T> Some(T) or None A value that may be missing
Result<T, E> Ok(T) or Err(E) An operation that may fail

You can write your own in exactly the same way:

rust · try it yourself
enum Reply<T> {
    Answer(T),
    NoIdea,
}

fn describe<T: std::fmt::Display>(r: Reply<T>) -> String {
    match r {
        Reply::Answer(v) => format!("The answer is {}", v),
        Reply::NoIdea => String::from("No idea, sorry"),
    }
}

fn main() {
    println!("{}", describe(Reply::Answer(42)));
    println!("{}", describe(Reply::Answer("blue")));
    println!("{}", describe::<i32>(Reply::NoIdea));
}
The answer is 42
The answer is blue
No idea, sorry

In the last call the compiler cannot work out T from Reply::NoIdea alone, so we tell it with the turbofish syntax describe::<i32>.

Do generics cost anything?

No run-time cost. Rust uses monomorphization: at compile time it generates a specialised copy of the generic code for each concrete type you use. largest::<f64> and largest::<&str> become two ordinary functions, as fast as if you had written them by hand.

Note: The trade-off is slightly larger binaries and longer compile times when a generic is used with many different types.

Test yourself

In fn show<T: Display>(x: T), what is T: Display?

  1. A lifetime
  2. A trait bound
  3. A type alias
  4. A macro

Which bound is needed to compare two generic values with >?

  1. Copy
  2. Clone
  3. PartialOrd
  4. Debug

What is monomorphization?

  1. Checking types at run time
  2. Generating a specialised copy of generic code for each concrete type
  3. Converting a struct into an enum
  4. Removing unused traits