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
Replay: real traced execution (multi-file project)
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}");
}
  1. nums ← [3, 7, 2, 9, 4]

    11fn main() {12    let num→ [3, 7, 2, 9, 4]s = [3, 7, 2, 9, 4];13    let biggest = largest(&num[3, 7, 2, 9, 4]s);14    println!("{biggest}");
  2. top ← (empty), items[0] ← (empty)

    1fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {2    let mut to→ (empty)p = items[0→ (empty)];3    for &item in items {
  3. for &item in items

    pass 1 of 5
    2let mut top = items[0];3for &item in item(empty)s {4    if item > top {
    All 5 passes — pass 1 is the card above
    passitemtop
    1
    2(empty)(empty)
    3
    4(empty)(empty)
    5
  4. if item > top

    pass 1 of 2
    3for &item in items {4    if ite(empty)m > to(empty)p {5        top = ite(empty)m;6    }
  5. if item > top

    pass 2 of 2
    3for &item in items {4    if ite(empty)m > to(empty)p {5        top = ite(empty)m;6    }
  6. top

    7    }8    to(empty)p9}
  7. biggest ← 9

    12    let nums = [3, 7, 2, 9, 4];13    let bigges→ 9t = largest(&num[3, 7, 2, 9, 4]s);14    println!("{biggest}");15}
    output9

Follow the Largest Value

  1. nums starts as [3, 7, 2, 9, 4].
  2. largest(&nums) starts top at the first value, 3.
  3. Seeing 7 updates top from 3 to 7.
  4. Seeing 9 updates top from 7 to 9.
  5. The helper returns 9, so the program prints 9. | value checked | top after check | | --- | --- | | 3 | 3 | | 7 | 7 | | 2 | 7 | | 9 | 9 | | 4 | 9 |
generic `largest<T>` works for any type `T`.
trait bound `T: PartialOrd + Copy` requires comparison and copy.
slice `&[T]` borrows a sequence of items.

Exercise: generics.rs

Reproduce the output 9, then trace how top changes from 3 to 7 to 9 while scanning [3, 7, 2, 9, 4].