Sub topic 1
Why Generics Exist
Generics let you write one function, struct, or enum that works for many types, while the compiler still checks every use. This chapter shows the problem they solve. Later chapters cover the syntax in detail.
Prerequisites
This chapter assumes you know the following:
- Basic Rust syntax: functions, structs, enums, and
letbindings. - Ownership and borrowing basics, including references like
&T. - What a trait is and how to implement one for a type.
- How to use
Option,Result, andVec.
The duplication problem
Suppose you need the largest value in a list. Without generics, you write one function per type.
fn largest_i32(items: &[i32]) -> &i32 {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn largest_char(items: &[char]) -> &char {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest_i32(&[3, 9, 2]));
println!("{}", largest_char(&['a', 'z', 'q']));
}The two bodies are identical. Only the type changed. If you find a bug in one, you must remember to fix the other. Add f64, u8, and String, and you maintain five copies.
Two ways to avoid copies, and their costs
Other languages remove this duplication in ways that cost something.
- Dynamic typing or a universal base type. One function accepts anything, such as
Objectin Java. You lose compile-time checks. A wrong type becomes a runtime error or needs a cast. - Type erasure with a runtime lookup. The code is shared, but each operation is resolved while the program runs. This adds indirection.
Rust generics avoid both costs. You write the code once with a placeholder for the type. The compiler checks it against the rules you state, then produces specialized code for each real type you use.
The generic version
Here is the same function written once.
fn largest<T: PartialOrd>(items: &[T]) -> &T {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest(&[3, 9, 2]));
println!("{}", largest(&[1.5, 0.2]));
println!("{}", largest(&['a', 'z', 'q']));
}T is a type parameter, a name that stands for some type chosen at each call. The part T: PartialOrd is a trait bound. It says T must support comparison with >. Without it, the compiler rejects item > largest, because it cannot know that an arbitrary T can be compared.
This is the key point. The compiler checks the generic function once, against the bound, not against each caller's type. A caller passing a type without PartialOrd gets an error at the call site.
The function still panics on an empty slice, because items[0] has no element to read. Generics do not change that. They remove duplicated code, not the need to handle edge cases.
What you get
- One copy of the logic. A fix applies to every type.
- Compile-time safety. Misuse is a compile error, not a runtime failure.
- No runtime penalty. The compiler generates a separate version for each type, so calls are direct. The monomorphization chapter explains this.
Exercise
Why does the compiler reject item > largest if you remove the PartialOrd bound from largest<T>?
Show answer
Without a bound, T could be any type, and the compiler cannot assume it supports >. The bound T: PartialOrd promises the comparison exists, so the generic body can be checked once for all valid types.
Exercise
What two costs do generics avoid compared with a single function that accepts a universal base type?
Show answer
They avoid losing compile-time type checking, since wrong types would only fail at runtime. They also avoid runtime indirection, since the compiler generates specialized code for each concrete type.