Sub topic 2
Generic Functions
This chapter assumes you can write and call ordinary Rust functions, use references (&T), implement a trait for a type, and work with Option and slices. It covers how to declare a generic function, how the compiler picks the concrete types, and the errors you will meet first.
The problem generic functions solve
Suppose you need the largest element of a slice. Without generics you write one function per element 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 bodies are identical. Only the types differ. A bug fix in one copy has to be repeated in the others. A generic function replaces the copies with one definition.
Declaring 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, and then use it in the signature:
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 in three parts:
<T: PartialOrd>declares a type parameter namedTand requires thatTimplementsPartialOrd.items: &[T]takes a borrowed slice of any element typeT.-> &Treturns a reference to one of those elements.
The name T is a convention. Any identifier works, and short descriptive names such as Item are fine when there are several parameters.
Why the bound is required
The body uses > on two &T values. The compiler checks a generic function once, against what it knows about T, and not separately for each caller. If you write fn largest<T>(items: &[T]) -> &T and leave out PartialOrd, the compiler rejects the > comparison with error E0369, because T might be a type that cannot be ordered. The compiler never tries to guess a bound from the body. You must state every capability the body relies on. Bounds get their own chapter, so here the rule is enough: if the body uses an operation, the signature must promise it.
The empty slice panics
largest indexes items[0], so an empty slice makes it panic at runtime. The type system cannot prevent this. A better signature returns Option:
fn largest_checked<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut iter = items.iter();
let mut best = iter.next()?;
for item in iter {
if item > best {
best = item;
}
}
Some(best)
}
fn main() {
let empty: [i32; 0] = [];
println!("{:?}", largest_checked(&empty));
println!("{:?}", largest_checked(&[3, 9, 2]));
}This prints None and then Some(9). The ? operator returns None early when the iterator has no first element.
How the compiler chooses T
At each call site the compiler infers T from the arguments. For largest(&[3, 9, 2]) it sees &[i32; 3], coerces it to &[i32], and picks T = i32. The integer literals default to i32 when nothing else constrains them.
flowchart LRBecause that line is not a valid diagram on its own, here is the full flow as a proper diagram block:
If the bound check fails, the error appears at the call site. For example, a slice of a type that does not implement PartialOrd cannot be passed to largest.
Return-only type parameters and the turbofish
Sometimes T appears only in the return type, so the arguments cannot tell the compiler what to pick. You then supply T yourself, either with a type annotation or with the turbofish syntax, ::<Type>:
fn zeroed<T: Default>() -> T {
T::default()
}
fn main() {
let a: i32 = zeroed();
let b = zeroed::<String>();
let n = "42".parse::<u8>().unwrap();
println!("{a} {b:?} {n}");
}This prints 0 "" 42. Without the annotation on a or the turbofish on b, the compiler reports that it cannot infer type T. The same syntax is how you write str::parse::<u8>, collect::<Vec<_>>(), and Vec::<i32>::new().
Several type parameters
List more than one parameter, separated by commas. Parameters are independent unless the signature reuses a name:
fn pair<A, B>(a: A, b: B) -> (A, B) {
(a, b)
}
fn bigger<T: PartialOrd>(a: T, b: T) -> T {
if a >= b { a } else { b }
}
fn main() {
let p = pair("age", 30);
println!("{:?}", p);
println!("{}", bigger(2, 7));
}pair accepts two unrelated types. bigger uses T twice, so both arguments must have the same type. Calling bigger(2, 7.5) fails with a mismatched types error, because an integer literal and a float literal cannot both be T. If you want to compare different types, you need two parameters and a bound that relates them, such as A: PartialOrd<B>.
The hidden Sized bound
Every type parameter has an implicit Sized bound, which means the compiler must know its size at compile time. That is why T can be passed by value. Types like str and [i32] have no fixed size, so they cannot be T by default. You can opt out with ?Sized, as long as the value stays behind a pointer:
use std::fmt::Debug;
fn show<T: Debug + ?Sized>(value: &T) {
println!("{value:?}");
}
fn main() {
show("hi");
show(&[1, 2, 3][..]);
show(&42);
}Here T is str in the first call, [i32] in the second, and i32 in the third.
Generic functions you already use
The standard library is full of generic functions. std::mem::swap<T>(a: &mut T, b: &mut T) swaps two values of the same type. std::cmp::max<T: Ord>(a: T, b: T) -> T is a bounded version of the bigger function above. Reading their signatures is good practice: the bounds list exactly what each function needs from its argument.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0369: binary operation cannot be applied to type `T` | The body uses an operator that the signature never promised | Add the matching bound, such as `T: PartialOrd` |
| Mismatched types on a second argument | The same `T` is used for both arguments, but the types differ | Use two type parameters, or convert one argument |
| Type annotations needed | `T` appears only in the return type or is otherwise unconstrained | Annotate the binding or use the turbofish |
| Cannot move out of a borrowed slice element | The function returns `T` by value from `&[T]` | Return `&T`, or add `T: Clone` and clone |
| Size not known at compile time | A `?Sized` type such as `str` was passed by value | Take `&T` and add `?Sized` |
Exercises
Exercise
Why does fn largest<T>(items: &[T]) -> &T fail to compile when the body contains if item > largest, and what is the smallest change that fixes it?
Show answer
The compiler checks the body against what it knows about T, and an unbounded T is not known to support >. Adding the bound T: PartialOrd to the type parameter (fn largest<T: PartialOrd>(...)) fixes it.
Exercise
Write the signature of a generic function first_or<T: Clone> that takes a slice &[T] and a fallback value of type T, and returns a T. Then say what first_or(&[], 5) needs in order to compile.
Show answer
fn first_or<T: Clone>(items: &[T], fallback: T) -> T, with a body like items.first().cloned().unwrap_or(fallback). Both the slice elements and the fallback share one T. The call first_or(&[], 5) compiles because the fallback 5 fixes T as an integer type (i32 by default), which the empty slice literal then adopts.
Exercise
For fn zeroed<T: Default>() -> T, why does let x = zeroed(); fail, and name two ways to fix it.
Show answer
No argument mentions T and nothing else in the program constrains it, so the compiler cannot infer it. Annotate the binding (let x: u64 = zeroed();) or use the turbofish (zeroed::<u64>()).