How do generics work in Rust

Generics in Rust enable writing reusable, type-safe code by using placeholders like T to define functions and structs that work with any data type.

Generics in Rust allow you to define functions, structs, and enums that work with any data type by using placeholders like T instead of concrete types. You declare a generic type parameter in angle brackets after the item name and use it wherever you would normally specify a type.

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

This largest function works for any type T that implements the PartialOrd trait, allowing you to compare values without duplicating code for i32, f64, or custom types.