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
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}");
}
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}");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 {for &item in items
pass 1 of 52let mut top = items[0];3for &item in item(empty)s {4 if item > top {All 5 passes — pass 1 is the card above pass itemtop1 — — 2 (empty) (empty) 3 — — 4 (empty) (empty) 5 — — if item > top
pass 1 of 23for &item in items {4 if ite(empty)m > to(empty)p {5 top = ite(empty)m;6 }if item > top
pass 2 of 23for &item in items {4 if ite(empty)m > to(empty)p {5 top = ite(empty)m;6 }top
7 }8 to(empty)p9}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
numsstarts as[3, 7, 2, 9, 4].largest(&nums)startstopat the first value,3.- Seeing
7updatestopfrom3to7. - Seeing
9updatestopfrom7to9. - The helper returns
9, so the program prints9. | 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].