Generics let you write code that works with multiple types while maintaining type safety.
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}struct Point<T> {
x: T,
y: T,
}
let integer_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };struct Point<T, U> {
x: T,
y: U,
}
let mixed = Point { x: 5, y: 4.0 };Generics have zero runtime cost in Rust! The compiler generates specialized code for each concrete type (monomorphization).
Constrain what types can be used:
fn print_debug<T: std::fmt::Debug>(item: T) {
println!("{:?}", item);
}
// Multiple bounds
fn compare<T: PartialOrd + Copy>(a: T, b: T) -> T {
if a > b { a } else { b }
}Implement a generic largest<T> function that finds the largest element in a slice.
PartialOrd + Copylargest(&[34, 50, 25, 100, 65]) → 100fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list {
if item > largest {
largest = item;
}
}
largest
}