Sub topic 3
Constraining generics with trait bounds
This chapter assumes you know Rust structs and functions, ownership and borrowing, and basic generics such as Vec<T>. It also assumes you can build and run a program with cargo.
Why generics need bounds
A generic function must work for every type that could replace T. Inside the function, the compiler only lets you do things that are valid for all such types. A bare T supports almost nothing, so you can't compare or print it.
A trait bound narrows T to types that implement a given trait. It also tells the compiler which operations are allowed on T.
A first bound
This function finds the largest item in a slice. It needs > to compare items and needs to copy items out of the slice.
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]));
println!("{}", largest(&['x', 'b']));
}PartialOrd provides >. Copy lets let mut max = items[0] and for &item in items duplicate values instead of moving them out of a borrowed slice. Join several bounds with +.
If you remove PartialOrd, the compiler rejects the comparison with error E0369: "binary operation > cannot be applied to type T". The fix is to add the bound. The error means the function body used something the signature didn't promise.
The function panics on an empty slice because of items[0]. A bound does not guard against that.
Where clauses
Long bounds make the signature hard to read. A where clause moves them after the parameter list. The meaning is identical.
use std::fmt::{Debug, Display};
fn report<T, U>(label: T, value: U) -> String
where
T: Display + Clone,
U: Debug,
{
format!("{label}: {value:?}")
}
fn main() {
println!("{}", report("scores", vec![1, 2, 3]));
}Use where when you have several type parameters or bounds that mention other types, such as where Vec<T>: Debug. That form can't be written inline.
Bounds on impl blocks
You can also bound an impl block. Methods in a bounded block exist only when the type meets the bound.
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 {}", self.a);
} else {
println!("largest is {}", self.b);
}
}
}
fn main() {
Pair::new(3, 8).show_largest();
}Every Pair<T> has new. Only a Pair<T> whose T is both Display and PartialOrd has show_largest.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "binary operation cannot be applied to type `T`" | The body uses an operator the signature doesn't promise | Add the trait that provides it, such as `PartialOrd` |
| "cannot move out of type `[T]`" | The code copies out of a slice, but `T` is not `Copy` | Add `Copy`, or use `Clone` and call `.clone()` |
| "the trait bound `X: Trait` is not satisfied" | The caller passed a type that lacks the implementation | Implement the trait for `X`, or pass a different type |
| "method not found" on a bounded type | The method comes from a trait that is not imported | Add a `use` for that trait |
Exercise
A function fn pick<T>(a: T, b: T) -> T { if a > b { a } else { b } } fails to compile. Which bound or bounds fix it, and why?
Show answer
Add T: PartialOrd, because > needs it. Returning a or b moves them, and each is used only once on each path, so Copy is not needed. The signature becomes fn pick<T: PartialOrd>(a: T, b: T) -> T.