Generic largest in Rust
A generic function with a trait bound, which is Rust's whole approach to polymorphism in miniature.
fn largest<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut iter = items.iter();
let mut best = iter.next()?;
for item in iter {
if item > best {
best = item;
}
}
Some(best)
}
Keywords and builtins used here
OptionPartialOrdSomefnforifinlargestletmut
The run, in numbers
- Lines
- 10
- Characters to type
- 178
- Tokens
- 64
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 37 seconds.
Step 2 of 4 in Generics, step 5 of 19 in Traits & generics.