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'.

Step 2 / 2

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 PartialOrd bound is what lets you write item > best for any T.
10_traits_generics.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
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
}