Sub topic 1
Why Generics Exist in Rust
Prerequisites
This chapter assumes basic Rust syntax, ownership and borrowing, traits, and common types such as Option, Result, and Vec.
Why Generics Exist
A generic is a placeholder for a concrete type. Generics let one definition work with several types while Rust still checks every use at compile time.
Without generics, you might write separate functions for the largest i32, f64, and char. Those functions would repeat the same algorithm. A generic function keeps the algorithm in one place:
fn largest<T: PartialOrd>(items: &[T]) -> &T {
let mut result = &items[0];
for item in items {
if item > result {
result = item;
}
}
result
}
fn main() {
println!("{}", largest(&[3, 9, 2]));
println!("{}", largest(&[1.5, 0.2]));
println!("{}", largest(&['a', 'z', 'q']));
}The T parameter represents an unknown type. The function can compare values because T has the PartialOrd trait bound. This example requires a nonempty slice because it indexes items[0].
Generic Functions
A type parameter appears in the function signature and connects its inputs and outputs:
fn first<T>(items: &[T]) -> Option<&T> {
items.first()
}Here, T can be any element type. The returned reference points into the input slice, so Rust checks that its lifetime is valid. A function can have multiple type parameters, such as fn pair<A, B>(a: A, b: B) -> (A, B).
Generic Structs and Enums
Structs and enums can also store values of different types without duplicating their definitions:
#[derive(Debug)]
struct Point<T> {
x: T,
y: T,
}
#[derive(Debug)]
enum Measurement<T> {
Known(T),
Missing,
}
fn main() {
let point = Point { x: 2, y: 4 };
let reading = Measurement::Known(9.5);
println!("{point:?}");
println!("{reading:?}");
}Point<i32> and Point<f64> are different concrete types. Rust ensures that both coordinates in each Point<T> use the same type.
Constraining Types with Trait Bounds
A type parameter is unrestricted until you add a bound. A trait bound states which operations or behavior the type must provide. Use bounds only for behavior the implementation needs. For example, PartialOrd enables comparison, while Debug enables formatted inspection.
Exercise
Why does largest need the PartialOrd bound?
Show answer
The function uses >, and PartialOrd provides the comparison operation for T.