Core Intermediate
10 Traits & generics
Traits are Rust's interfaces; generics let one function serve many types. Give a trait a default method, then write a generic 'largest'.
Write a generic largest over a non-empty slice.
Hints
- Start with the first element as the best, then scan the rest and replace it when you find bigger.
- The
PartialOrdbound is what lets you writeitem > bestfor anyT.
Reveal solution
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut best = items[0];
for &item in &items[1..] {
if item > best {
best = item;
}
}
best
}