Sub topic 4
Constraining types with trait bounds
This chapter assumes you know basic Rust syntax, ownership and borrowing, how to implement a trait for a type, and how to use Option and Vec. You should also have seen a generic function such as fn first<T>(items: &[T]) -> &T.
Why an unconstrained `T` can do almost nothing
Inside a generic function, the compiler knows nothing about T except that it exists. It can't assume T can be compared, printed, copied, or added. A bare T can only be moved, or borrowed through a reference.
Suppose you write a largest function with T and no bound, and use > on two items. The compiler rejects it:
error[E0369]: binary operation `>` cannot be applied to type `&T`
help: consider restricting type parameter `T` with trait `PartialOrd`Rust checks a generic function once, against its signature, and not once per call. The signature therefore has to list every capability the body uses. A trait bound is that list. It says that a type parameter must implement a given trait.
Basic syntax
Write the bound after the type parameter, separated by a colon:
fn largest<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() {
println!("{:?}", largest(&[3, 9, 2]));
println!("{:?}", largest(&[1.5, 0.2]));
println!("{:?}", largest::<char>(&[]));
}T: PartialOrd means that any caller must pick a T that implements PartialOrd. In exchange, the body may use <, >, <=, and >= on values of type T.
This version returns Option<&T> instead of indexing items[0], so an empty slice returns None and does not panic. The turbofish ::<char> on the last call is needed because an empty array literal gives the compiler nothing to infer T from.
Bounds are checked at the call site. Calling largest with a type that lacks PartialOrd fails to compile, and the error points at the call, not at the body of largest.
Several bounds with `+`
Join bounds with + when the body needs more than one capability:
use std::fmt::Display;
fn report<T: Display + Clone>(value: &T) -> String {
let copy = value.clone();
format!("[{copy}]")
}
fn main() {
println!("{}", report(&42));
println!("{}", report(&String::from("hi")));
}The type must satisfy all of the bounds. Once a signature collects three or four of them, it gets hard to read. The next chapter covers where clauses, which solve that. Inline bounds are fine for one or two.
Bounds from your own traits
Bounds are not limited to standard library traits. Any trait you define works the same way:
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.0 * self.0
}
}
fn total_area<S: Shape>(shapes: &[S]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
println!("{}", total_area(&[Square(2.0), Square(3.0)]));
println!("{}", total_area(&[Circle(1.0)]));
}A single S stands for one concrete type per call. total_area(&[Square(2.0), Circle(1.0)]) does not compile, because the array would need two different element types. If you need a mixed collection, use trait objects (Box<dyn Shape>), which a later chapter covers.
What the compiler checks
Bounds that unlock operators
Operators are traits in std::ops. To use + on a T, you need Add. Add has an associated type, Output, which says what a + b produces. Most numeric code wants the result to be T again, so you write Add<Output = T>:
use std::ops::Add;
fn sum_all<T: Add<Output = T> + Default + Copy>(items: &[T]) -> T {
let mut total = T::default();
for &item in items {
total = total + item;
}
total
}
fn main() {
println!("{}", sum_all(&[1, 2, 3]));
println!("{}", sum_all(&[0.5, 0.25]));
}Each bound has a job:
Defaultsupplies a starting value throughT::default().Copyletsfor &item in itemscopy each element out of the borrowed slice.Add<Output = T>letstotal + itemproduce anotherT.
Choosing between `Copy` and `Clone`
Moving a value out of a borrowed slice is an error for non-Copy types. The bound you choose decides which types can use the function:
fn first_copy<T: Copy>(items: &[T]) -> Option<T> {
items.first().copied()
}
fn first_clone<T: Clone>(items: &[T]) -> Option<T> {
items.first().cloned()
}
fn main() {
println!("{:?}", first_copy(&[7, 8]));
let words = vec![String::from("a"), String::from("b")];
println!("{:?}", first_clone(&words));
// first_copy(&words) would not compile: String is not Copy.
}Clone accepts more types, because every Copy type is also Clone. It can allocate, though, and callers can see that cost. Choose the weakest bound that lets the body compile. A weaker bound accepts more callers.
Bounds on impl blocks: conditional methods
A bound on an impl block makes the methods inside it available only when the bound holds:
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, 7).show_largest();
let vectors = Pair::new(vec![1], vec![2]);
let _ = (&vectors.a, &vectors.b);
// vectors.show_largest() would not compile: Vec<i32> is not Display.
}Pair<Vec<i32>> exists and has new, but not show_largest. The type stays usable for any T. Only the methods that need more get restricted.
This is also why the standard library can offer Vec::sort only when T: Ord, while Vec::push works for every T.
Where to put bounds
Put bounds on functions and impl blocks. Avoid putting them on struct definitions, such as struct Pair<T: Display>. A bound on the struct is repeated on every impl block and every function that mentions the type, even where the code never uses the bound. Many standard types, such as Vec<T> and HashMap<K, V>, put no bounds on the type itself and add them only on the methods that need them.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `binary operation cannot be applied to type T` | The body uses an operator, but the trait is not in the bound. | Add `PartialOrd`, `PartialEq`, `Add<Output = T>`, or the matching trait. |
| `cannot move out of ... which is behind a shared reference` | The body copies or moves a `T` out of `&[T]` or `&T`. | Add `Copy`, or add `Clone` and call `.clone()`. |
| `the trait bound X: Trait is not satisfied` at a call | The caller's type doesn't implement the trait. | Implement the trait for the type, or pick a different type. |
| `T` has no method `m` | The method belongs to a trait that isn't in the bound. | Add the bound. A trait must also be in scope with `use` to call its methods. |
| `the size for values of type T cannot be known` | You used `T` in a position that must be sized, such as `str` passed as `T`. | Pass a reference such as `&T`, or relax the bound with `?Sized`. |
Details worth knowing
Every generic type parameter has an implicit Sized bound, so T cannot be str or [u8] unless you write T: ?Sized. You will rarely write that, but it explains why fn f<T>(x: &T) rejects f("hello") when T would have to be str, unless you add ?Sized.
Floats implement PartialOrd but not Ord, because NaN is not comparable to anything. A function bounded on T: Ord therefore rejects f64. A function bounded on T: PartialOrd accepts it, and returns false for any comparison involving NaN.
Exercise
Write a generic function smallest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> that returns the smallest element, or None for an empty slice. Why is Copy needed here, and what would you change to accept String elements?
Show answer
Body: let mut iter = items.iter(); let mut best = *iter.next()?; for &item in iter { if item < best { best = item; } } Some(best). Copy is needed because *iter.next()? and for &item copy values out of a borrowed slice, and moving out of a borrow is an error. To accept String, replace Copy with Clone and use .clone() where the values are taken, or return Option<&T> and need neither bound.
Exercise
Given struct Wrapper<T>(T);, you write impl<T: std::fmt::Display> Wrapper<T> { fn show(&self) -> String { format!("{}", self.0) } }. Can you call show on Wrapper(vec![1, 2])? Can you construct that Wrapper?
Show answer
You cannot call show, because Vec<i32> does not implement Display, so the method does not exist for that instantiation. You can construct Wrapper(vec![1, 2]), because the struct has no bounds on T.