Sub topic 3
Constraining generics with trait bounds
This chapter assumes you can define and implement a trait, including default methods. It also assumes you know basic generics such as Vec<T> and Option<T>, and the ownership rules for moving and copying values.
Why a generic type needs bounds
Inside a generic function, T could be any type. The compiler therefore lets you do nothing with a T value except move it around. You can't compare two T values, print one, or copy one. A trait bound states what T must be able to do. The compiler then allows exactly those operations in the body. It also rejects any call whose concrete type doesn't meet the bound.
The bound is part of the function's signature. A caller can read what the function requires without opening the body. The compiler checks the body against the signature alone, not against the types a caller happens to pass.
Inline bounds
An inline bound goes after the type parameter. Several bounds are joined with +.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T {
let mut max = items[0];
for &item in items {
if item > max {
max = item;
}
}
max
}
fn main() {
println!("{}", largest(&[3, 9, 4]));
println!("{}", largest(&[1.5, 0.2]));
}Each bound is needed:
PartialOrdprovides>. Without it,item > maxfails with error E0369 (binary operation cannot be applied to typeT).Copyletsitems[0]andfor &item in itemstake values out of the slice. Without it, the compiler reports E0508 (cannot move out of type[T]), because you would be moving out of borrowed data.
The call largest(&[3, 9, 4]) shows how the check works. The compiler infers T = i32 from the argument. It then confirms i32: PartialOrd and i32: Copy, and generates code for i32.
Relaxing Copy with Clone
Copy excludes types that own heap data, such as String and Vec<T>. If you only need duplicates, Clone is the weaker bound. It accepts more types, at the cost of explicit .clone() calls.
fn largest_clone<T: PartialOrd + Clone>(items: &[T]) -> T {
let mut max = items[0].clone();
for item in items {
if *item > max {
max = item.clone();
}
}
max
}
fn main() {
let words = [String::from("pear"), String::from("apple")];
println!("{}", largest_clone(&words));
}If you want to avoid copying altogether, return &T and drop both Copy and Clone. Only PartialOrd remains necessary.
where clauses
A where clause moves the bounds out of the angle brackets. The meaning is the same. It matters in three situations:
- Several parameters each carry several bounds, and the signature becomes hard to read.
- You need to bound something other than a bare type parameter.
- You want a bound on an associated type.
use std::fmt::Display;
fn print_all<I>(iter: I)
where
I: IntoIterator,
I::Item: Display,
{
for item in iter {
println!("{item}");
}
}
fn main() {
print_all(vec![1, 2, 3]);
print_all(["a", "b"]);
}The bound I::Item: Display cannot be written inline, because I::Item is not a type parameter. It is a type that depends on I. Associated types get their own chapter. For now, read I::Item as "the type of element that I produces."
Bounds on impl blocks
Bounds also apply to impl blocks. Methods in an impl<T: Bound> block exist only for types that meet the bound. This is called a conditional implementation.
use std::fmt::Display;
struct Pair<T> {
a: T,
b: T,
}
impl<T> Pair<T> {
fn new(a: T, b: T) -> Self {
Pair { a, b }
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn show_largest(&self) {
if self.a >= self.b {
println!("largest is a = {}", self.a);
} else {
println!("largest is b = {}", self.b);
}
}
}
fn main() {
Pair::new(3, 8).show_largest();
Pair::new("x", "y").show_largest();
}Pair::new works for every T. show_largest exists only when T is both Display and PartialOrd. A Pair<Vec<i32>> can be built, since Vec<i32> is PartialOrd, but it has no show_largest, because Vec<i32> is not Display. Calling the method on it fails at compile time with a message that names the unmet bound.
Bounds across more than one type
Each type parameter has its own bounds, and bounds can name other types. T: PartialEq<U> means "a T can be compared with a U." Plain PartialEq is shorthand for PartialEq<Self>. If a function takes two different type parameters and compares them with only T: PartialEq, the compiler rejects it. It reports a type mismatch because it expects the same type on both sides.
You can also require a bound on a reference type. For example, where for<'a> &'a T: Add<&'a T> says that adding two references to T is allowed. This is rare, but it is the way to write generic arithmetic that doesn't consume its inputs.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0369, binary operation not applicable to `T` | An operator is used without its trait bound | Add `PartialOrd`, `Add<Output = T>`, or the relevant trait |
| E0508 or E0507, cannot move out of borrowed content | A value is taken out of `&[T]` or `&T` without `Copy` | Add `Copy`, or use `Clone` and `.clone()`, or return a reference |
| E0277, trait bound not satisfied at the call site | The concrete type lacks an impl | Implement the trait for the type, or pass a different type |
| E0599, method exists but its trait bounds were not satisfied | The method is in a conditional `impl` block | Make the type satisfy all of that block's bounds |
| E0282 or E0283, type annotations needed | The compiler cannot infer `T` from the arguments | Annotate: `largest::<i32>(&[])` |
Two habits reduce these errors. Add bounds when the compiler asks for them, not before. Then read the E0277 note carefully, because it states which bound failed and which type failed it. Don't over-constrain either. T: Copy where Clone or no bound would do shuts out String and every other owning type for no reason.
Bounds and the generated code
A bounded generic function is compiled once per concrete type it is called with. largest::<i32> and largest::<f64> are separate machine-code functions. This is why a bound costs nothing at run time. The next chapters cover this in detail, along with the alternative that trades speed for flexibility.
Exercise
The call largest(&[String::from("a"), String::from("b")]) fails to compile with the largest function above, which has the bound T: PartialOrd + Copy. Which bound is the problem, and how would you change the signature so Strings work without cloning?
Show answer
String is PartialOrd but not Copy, so the Copy bound is unmet (error E0277). To avoid cloning, return a reference: fn largest<T: PartialOrd>(items: &[T]) -> &T. Start with let mut max = &items[0];, loop with for item in items, compare item > max, and assign max = item. Only PartialOrd is required.