title: Generics

Generics let you write code that works with multiple types without duplicating it. Instead of writing the same function twice for i32 and f64, you write it once and let the caller decide the type.

The problem they solve

Without generics you’d need a separate function for every type:

fn largest_i32(list: &[i32]) -> i32 { ... }
fn largest_f64(list: &[f64]) -> f64 { ... }

With generics, one function covers both:

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

The <T> is a placeholder that means “some type, to be decided later.” T is just a convention — you could use any name.

Generic functions

fn first<T>(list: &[T]) -> &T {
    &list[0]
}
 
let numbers = vec![1, 2, 3];
let words = vec!["hello", "world"];
 
first(&numbers);  // T is inferred as i32
first(&words);    // T is inferred as &str

The compiler fills in the real type at compile time — there’s no runtime cost.

Generic structs

struct Pair<T> {
    first: T,
    second: T,
}
 
let ints = Pair { first: 1, second: 2 };
let strs = Pair { first: "hello", second: "world" };

You can use multiple type parameters:

struct Pair<T, U> {
    first: T,
    second: U,
}
 
let mixed = Pair { first: 1, second: "hello" };

Bounds — restricting what T can be

A plain <T> accepts any type, but sometimes you need the type to support certain operations. You express this with a trait bound:

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

T: PartialOrd means “T must be a type that supports comparison with >.” If you pass a type that can’t be compared, the compiler rejects it.

Multiple bounds use +:

fn print_largest<T: PartialOrd + std::fmt::Display>(list: &[T]) { ... }

No runtime cost

Rust resolves generics at compile time through a process called monomorphization — it generates a separate version of the function for each concrete type you use. You get the flexibility of generics with the performance of hand-written specific code.