Traits and Generics
Generics
One Function, Many Types
A generic function works for any type that satisfies its trait bounds. Here it finds the largest item in a slice.
Program
Play the program to find the largest number with a generic helper.
generics.rs
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut top = items[0];
for &item in items {
if item > top {
top = item;
}
}
top
}
fn main() {
let nums = [3, 7, 2, 9, 4];
let biggest = largest(&nums);
println!("{biggest}");
}
generic
`largest<T>` works for any type `T`.
trait bound
`T: PartialOrd + Copy` requires comparison and copy.
slice
`&[T]` borrows a sequence of items.