Sub topic 4
Constraining types with trait bounds
This chapter assumes you can write basic generic functions with <T>, implement a trait for a type, and borrow with &T.
An unbounded T can do nothing
A bare type parameter T could be any type. The compiler therefore lets you do nothing with a T value except move it, borrow it, or take its size. This function looks reasonable but does not compile:
fn largest<T>(items: &[T]) -> &T {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}error[E0369]: binary operation `>` cannot be applied to type `&T`
help: consider restricting type parameter `T` with trait `PartialOrd`Not every type can be compared with >, so the compiler rejects the function before any caller exists. This is the main difference from C++ templates, which are checked only when instantiated.
Adding a bound
A trait bound says "T can be any type, as long as it implements this trait." You write it after a colon in the type parameter list:
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']));
}Inside the body, the compiler now allows everything PartialOrd provides, including >. At each call site, it checks that the concrete type implements PartialOrd. Note that items[0] panics on an empty slice.
Combining bounds
Join several bounds with +. The type must implement all of them:
use std::fmt::Display;
fn announce<T: Display + Clone>(value: &T) -> T {
println!("value = {value}");
value.clone()
}
fn main() {
let name = announce(&String::from("Ferris"));
let n = announce(&42);
println!("{name} {n}");
}Display allows the {value} formatting. Clone allows value.clone(), which returns an owned T from a reference.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0369, binary operation cannot be applied to `T` | The body uses an operator the bounds do not provide | Add the trait, such as `PartialOrd` or `Add<Output = T>` |
| E0277, trait bound not satisfied | The caller's type does not implement the trait | Implement the trait for that type, or pass a different type |
| E0508 or E0507, cannot move out of a slice or reference | The body copies a `T` out of a borrow | Return `&T`, or add `Copy` or `Clone` |
| E0599, method not found for `T` | The method belongs to a trait that is not in the bounds | Add that trait as a bound |
The third row is a frequent surprise. This version returns T by value, so it needs Copy:
fn largest_copy<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut largest = items[0];
for &item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest_copy(&[4, 8, 1]));
}Exercise
Write the signature of a generic function larger that takes two values of the same type and returns the larger one by value. Which bounds does it need, and why?
Show answer
fn larger<T: PartialOrd + Copy>(a: T, b: T) -> T. PartialOrd provides the comparison. Copy is not needed to return a or b as they are, because both are owned parameters. Without Copy, the function still works if its body is if a >= b { a } else { b }. The strictly minimal signature is therefore fn larger<T: PartialOrd>(a: T, b: T) -> T.