WeCodeAcademy

Rust Generics

Generics let you write code once for many types. Add trait bounds to say what the type must be able to do.

ExampleRust
use std::fmt::Display;

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

fn show_pair<T: Display, U: Display>(a: T, b: U) -> String {
    format!("({}, {})", a, b)
}

struct Wrapper<T> {
    value: T,
}

impl<T: Display> Wrapper<T> {
    fn describe(&self) -> String {
        format!("wrapping {}", self.value)
    }
}

fn main() {
    println!("{}", largest(&[3, 9, 4]));
    println!("{}", largest(&[1.5, 0.2]));
    println!("{}", show_pair("x", 42));
    println!("{}", Wrapper { value: "box" }.describe());
}
Output
9
1.5
(x, 42)
wrapping box
Quick check

What does a trait bound like T: Display say?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.