Generics
A generic function works with a type that's decided at the call site, not when it's defined. T: PartialOrd + Copy restricts T to types that can be compared and copied — exactly what largest needs to work, and nothing more.
main.rs
Try it yourself →fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut largest = items[0];
for &item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![10, 25, 3, 47, 8];
println!("largest number: {}", largest(&numbers));
let chars = vec!['y', 'm', 'a', 'q'];
println!("largest char: {}", largest(&chars));
}Output
largest number: 47 largest char: y
Generic structs
Structs can be generic too — Point<T> works for any type T, with both fields sharing the same type. The impl block's own T: std::fmt::Display bound only applies to describe, so Point itself stays usable even with types that can't be displayed.
main.rs
Try it yourself →struct Point<T> {
x: T,
y: T,
}
impl<T: std::fmt::Display> Point<T> {
fn describe(&self) -> String {
format!("({}, {})", self.x, self.y)
}
}
fn main() {
let int_point = Point { x: 3, y: 4 };
let float_point = Point { x: 1.5, y: 2.5 };
println!("{}", int_point.describe());
println!("{}", float_point.describe());
}Output
(3, 4) (1.5, 2.5)
Next: error handling — propagating a Result with ?, and writing a custom error type.
Practice exercise
Write a generic function first<T: Copy>(items: &[T]) -> T that returns the first item in a slice, then print first(&[10, 20, 30]).