Sub topic 1
Why Generics Exist
Generics let you write one function, struct, or enum that works for many concrete types, while the compiler still checks every use. This chapter explains the problem they solve, shows the duplication they remove, and sets up the vocabulary for the rest of the tutorial.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: functions, structs, enums, and
letbindings. - Ownership and borrowing basics, including references such as
&T. - What a trait is and how to implement one for a type.
- How to use
Option,Result, andVec.
You do not need to know trait bounds, where clauses, or lifetimes in detail. Later chapters cover them.
The problem: the same code for different types
Suppose you need the largest number in a list of i32 values. You write this:
fn largest_i32(items: &[i32]) -> &i32 {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest_i32(&[3, 9, 2]));
}Later you need the largest f64, then the largest char. The body of the function would be identical each time. Only the type in the signature changes.
fn largest_f64(items: &[f64]) -> &f64 {
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_f64(&[1.5, 0.2]));
println!("{}", largest_char(&['a', 'z', 'q']));
}Copying code like this has real costs:
- A bug fix has to be applied in every copy, and it is easy to miss one.
- The number of functions grows with the number of types.
- Readers must compare the copies to confirm they really do the same thing.
Two ways to avoid duplication, and why Rust picks a third
Other languages remove this duplication in different ways. Comparing them shows what generics are for.
| Approach | How it works | Cost |
|---|---|---|
| Copy and paste per type | One function per type | Duplication and drift between copies |
| Erase the type (a common base type, or `void*` in C) | One function that accepts "anything" | Type errors move to run time, or need casts |
| Generics | One function with a type parameter | The compiler generates the per-type code for you |
Rust generics give you the single definition of the second approach and the type safety of the first. The compiler checks that each use makes sense for the concrete type, and it does so at compile time.
The idea: a type parameter
A type parameter is a placeholder for a type that the caller chooses. You declare it in angle brackets after the function name, then use it where a concrete type would go.
Here is the three-function problem solved with one function:
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']));
}Read the signature piece by piece:
<T: PartialOrd>declares a type parameter namedT. The part after the colon is a trait bound. It saysTmust implementPartialOrd, the trait that provides>,<, and related comparisons.items: &[T]is a borrowed slice whose elements have typeT.-> &Treturns a reference to one of those elements.
The program prints 9, 1.5, and z. The compiler infers T at each call: i32 for the first, f64 for the second, char for the third. You rarely write the type yourself.
Two details are worth noting now:
largestpanics on an empty slice, becauseitems[0]is out of range. Generics change which types are accepted, not how the body behaves. A production version would returnOption<&T>.- The name
Tis a convention for "type". Any identifier works, but short capital names such asT,U, andEare the norm.
Why the bound is required
Remove : PartialOrd and the function no longer compiles:
fn largest<T>(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]));
}The compiler rejects the comparison with an error like binary operation '>' cannot be applied to type '&T', and suggests restricting T with std::cmp::PartialOrd.
This is a key difference from templates in C++. A C++ template is only checked when you instantiate it, so an error can appear far from the template's definition. Rust checks a generic function once, against its declared bounds. Inside the body, T can do only what the bounds promise. With no bounds, you cannot compare values, print them, or copy them. You can only move them around or take references to them.
That restriction is a feature. The signature tells callers exactly what a type must support, and a call that satisfies the signature cannot fail inside the body for type reasons.
Generics are already everywhere
You have used generics before, probably without naming them. The standard library defines its core types this way:
fn main() {
let numbers: Vec<i32> = vec![1, 2, 3];
let names: Vec<String> = vec![String::from("Ada"), String::from("Grace")];
let found: Option<&i32> = numbers.first();
let parsed: Result<u8, std::num::ParseIntError> = "200".parse::<u8>();
println!("{:?} {:?} {:?} {:?}", numbers, names, found, parsed);
}Vec<T>, Option<T>, and Result<T, E> are generic types. One definition of Vec<T> serves every element type, and Vec<i32> and Vec<String> are distinct types the compiler will not let you mix. Without generics, the standard library would need a separate vector type for each element type, or would have to store untyped values and check them at run time.
What the compiler does for you
You write the function once. When you call largest with i32, f64, and char, the compiler produces a specialized version for each type. This process is called monomorphization, and a later chapter covers it in detail. The result is that a generic call runs as fast as the hand-written copy would have. Rust describes this as a zero-cost abstraction: you pay nothing at run time for having written the code generically.
The trade-off moves to compile time and binary size. Each distinct type used with a generic function adds another compiled copy. For most programs this is a good bargain, but it is why the tutorial later compares generics with trait objects.
Common mistakes
- Forgetting a bound. If the body uses an operation such as
>,+,{}printing, or.clone(), the type parameter needs the matching trait bound. The compiler error names the missing trait. - Expecting generics to accept mixed types.
largest(&[1, 2.5])fails because all elements of a slice share one type. A singleTstands for one type per call. - Reaching for generics too early. If a function only ever handles one type, make it concrete. Add a type parameter when a second real use appears.
- Assuming
Tcan be unsized. By default every type parameter must have a size known at compile time. Later chapters show the?Sizedrelaxation.
What comes next
The rest of this tutorial builds on this one idea. You will write generic functions and types, constrain them with trait bounds and where clauses, and write impl blocks that apply to all or only some instantiations. You will then look at monomorphization, impl Trait, and the choice between generics and trait objects. The final chapters cover lifetimes alongside type parameters, associated types, blanket implementations, const generics, default type parameters, and PhantomData.
Exercise
The function fn first<T>(items: &[T]) -> &T { &items[0] } compiles without any trait bound, but fn bigger<T>(a: T, b: T) -> T { if a > b { a } else { b } } does not. Why, and what is the smallest change that fixes the second one?
Show answer
first only indexes the slice and returns a reference, which every type supports, so T needs no capabilities. bigger uses >, which requires the type to implement PartialOrd. Change the signature to fn bigger<T: PartialOrd>(a: T, b: T) -> T. Because a and b are taken by value and returned by value, no Copy or Clone bound is needed, since each is moved into exactly one branch.
Exercise
Why does largest(&[1, 2.5]) fail to compile even though largest is generic?
Show answer
A slice holds elements of a single type, so the array literal [1, 2.5] cannot mix an integer and a float. The type parameter T stands for one concrete type per call, not for several types at once. Writing [1.0, 2.5] makes every element f64 and the call compiles.