What Are Generic Types in Rust?

Generic types in Rust are placeholders that let you write flexible, reusable code for any data type without duplication.

Generic types in Rust are placeholders for specific types that you specify later, allowing you to write flexible, reusable code without duplicating logic for every data type. You define them using angle brackets and a placeholder name like T in functions, structs, or enums.

struct Point<T> {
    x: T,
    y: T,
}

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