One algorithm, many concrete types.
Express reusable code without discarding type information.
01 Understand the contract
A generic parameter stands for a type chosen by the caller or inferred from usage. The function body still has to be valid for its declared bounds. Rust normally monomorphizes generic functions into concrete versions used by the program, so generic code does not automatically imply dynamic dispatch. Start with the operations the algorithm needs and express those as bounds. Prefer a small clear generic function over a highly abstract signature that makes everyday calls hard to understand.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn first<T>(values: &[T]) -> Option<&T> {
values.first()
}
fn main() {
println!("{:?}", first(&[3, 5]));
println!("{:?}", first(&["Rust", "Python"]));
}Some(3)
Some("Rust")- 1
T is inferred separately at the two calls.
- 2
The function borrows any element type.
- 3
No Copy bound is necessary because it returns a reference.
cargo run -p lesson_generics03 Mind the boundary
04 Your next build
Write last<T> returning an optional reference and test it with integers and an empty slice.
Reveal one possible solution +
fn last<T>(values: &[T]) -> Option<&T> {
values.last()
}
fn main() {
assert_eq!(last(&[2, 7]), Some(&7));
assert_eq!(last::<u8>(&[]), None);
}05 Check your reasoning
Why does first<T> not need T: Copy?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.