Sub topic 3
Constraining Associated Types in Bounds and Where Clauses
This chapter assumes you can define and implement traits, write generic functions with trait bounds, and use Iterator with for loops and adapters. You should also have read the previous chapter on declaring and implementing associated types. Here you learn how to put conditions on an associated type, so generic code can rely on what it needs and nothing more.
Why a bound on the trait is not enough
Consider a function that sums the items of any iterator:
fn sum_all<I: Iterator>(iter: I) -> u32 {
iter.sum()
}This does not compile. I: Iterator says that I has some Item type, but it does not say which one. The compiler cannot know that Item can be summed into a u32. You need a way to say something about I::Item. Rust gives you three tools:
- An equality constraint, written
Iterator<Item = u32>, which fixes the associated type. - A bound on the associated type, written
I::Item: Display, which requires it to implement a trait. - A bound declared in the trait itself, written
type Item: Display;, which every implementer must satisfy.
Equality constraints: `Trait<Name = Type>`
An equality constraint goes inside the angle brackets of the trait in a bound. It names the associated type and says what it must be.
struct Countdown(u32);
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.0 == 0 {
None
} else {
self.0 -= 1;
Some(self.0 + 1)
}
}
}
fn sum_all<I>(iter: I) -> u32
where
I: Iterator<Item = u32>,
{
iter.sum()
}
fn main() {
println!("{}", sum_all(Countdown(3)));
}This prints 6. The bound I: Iterator<Item = u32> accepts Countdown because its Item is u32. It rejects an iterator over String with a type mismatch error (E0271, "type mismatch resolving <I as Iterator>::Item == u32").
You can bind the associated type to another type parameter. This is how you extract the element type:
use std::collections::HashMap;
use std::hash::Hash;
fn index_pairs<K, V, I>(pairs: I) -> HashMap<K, V>
where
I: Iterator<Item = (K, V)>,
K: Eq + Hash,
{
pairs.collect()
}
fn main() {
let map = index_pairs(vec![("a", 1), ("b", 2)].into_iter());
println!("{}", map["b"]);
}Here K and V are inferred from the iterator's Item. The caller never writes them.
Equality constraints on operators
Operator traits use the same syntax. Add has a generic parameter for the right-hand side and an associated type Output for the result. The bound Add<Output = T> requires the sum to have the same type as the input.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
fn double<T: Add<Output = T> + Copy>(value: T) -> T {
value + value
}
fn main() {
println!("{:?}", double(Point { x: 1, y: 2 }));
}The function needs Copy because value + value uses value twice, and add takes self by value. Without Output = T, the result of value + value would have an unknown type and could not be returned as T.
The output type does not have to equal the input type. You can introduce a second parameter:
use std::ops::Add;
fn add_pair<T, U>(a: T, b: T) -> U
where
T: Add<Output = U>,
{
a + b
}
fn main() {
let total: i64 = add_pair(2_i64, 3_i64);
println!("{}", total);
}Bounds on an associated type
An equality constraint pins down the exact type. Often you only need the type to have some capability. For that, write a bound on the path I::Item in a where clause:
use std::fmt::Display;
fn print_all<I>(iter: I)
where
I: Iterator,
I::Item: Display,
{
for item in iter {
println!("{}", item);
}
}
fn main() {
print_all(vec![1, 2, 3].into_iter());
print_all(["a", "b"].iter());
}This accepts any iterator whose items can be displayed. It accepts both i32 items and &&str items, because references to Display types are themselves Display.
You can also relate the associated types of two parameters:
fn same_items<A, B>(a: A, b: B) -> bool
where
A: Iterator,
B: Iterator<Item = A::Item>,
A::Item: PartialEq,
{
a.eq(b)
}
fn main() {
println!("{}", same_items(1..4, vec![1, 2, 3].into_iter()));
}The bound B: Iterator<Item = A::Item> mixes both tools. It is an equality constraint whose right side is a path to another associated type.
Why a `where` clause is often required
You can write simple bounds inline, as in I: Iterator<Item = u32>. A bound on a path such as I::Item: Display can only appear in a where clause. The same holds for any bound whose left side is not a bare type parameter. Prefer a where clause as soon as the bounds get long, because it separates the list of parameters from the list of conditions.
Bounds declared in the trait
When every implementer must provide an associated type with certain capabilities, state this once in the trait:
use std::fmt::Debug;
trait Shape {
type Unit: Debug + Copy;
fn unit(&self) -> Self::Unit;
}
struct Circle;
impl Shape for Circle {
type Unit = f64;
fn unit(&self) -> f64 {
1.0
}
}
fn show<S: Shape>(shape: &S) {
println!("{:?}", shape.unit());
}
fn main() {
show(&Circle);
}Two things happen with type Unit: Debug + Copy;.
- Each
implis checked. If you wrotetype Unit = String;, the compiler would report thatStringdoes not implementCopy, at theimpl. - Generic code gets the bounds for free. In
show, the boundS: Shapeis enough to call{:?}onshape.unit(). You do not repeatS::Unit: Debug.
Compare this with a bound in a function's where clause. A bound in a function affects only that function. A bound in the trait is a promise made by all implementers and available to all users. Put a bound in the trait when every sensible implementer satisfies it. Put it on the function when only some callers need it. Over-constraining the trait forces extra requirements on every implementer. Iterator itself puts no bounds on Item for this reason.
You can also use a where clause inside the trait, for example where Self::Item: Debug on a method. That limits the method to implementers whose type qualifies, while the trait stays open to others.
Supertraits and constraints
A supertrait bound can include an equality constraint. This makes a trait that only exists for one item type:
trait ByteSource: Iterator<Item = u8> {
fn checksum(&mut self) -> u8 {
self.fold(0u8, |acc, b| acc.wrapping_add(b))
}
}
impl<I: Iterator<Item = u8>> ByteSource for I {}
fn main() {
let mut bytes = vec![200u8, 100, 5].into_iter();
println!("{}", bytes.checksum());
}Inside checksum, the compiler knows Self::Item is u8, so fold with a u8 accumulator type-checks. The blanket impl makes every byte iterator a ByteSource.
`impl Trait` uses the same syntax
In argument and return position, impl Trait accepts the same constraints:
fn evens(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0)
}
fn total(iter: impl Iterator<Item = u32>) -> u32 {
iter.sum()
}
fn main() {
println!("{}", total(evens(10)));
}The caller of evens sees only "some iterator of u32". Use the named-parameter form instead when you need to refer to the type again, for example B: Iterator<Item = A::Item>.
How the compiler checks a call
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "associated type `Item` not found for `T`" | `T` has no bound that provides `Item` | Add `T: Iterator` before using `T::Item` |
| E0271 "type mismatch resolving ..." | The equality constraint does not match the implementer's type | Change the argument, or loosen the bound to `I::Item: Trait` |
| "the trait bound `I::Item: Display` is not satisfied" | The function uses a capability that was never declared | Add `I::Item: Display` to the `where` clause |
| "ambiguous associated type" | Several traits in scope could provide the name | Use the qualified path `<T as Trait>::Name` (next chapters cover it) |
| `Output` does not match after `a + b` | Only `Add` was required, not `Add<Output = T>` | Add the equality constraint |
Exercises
Exercise
Write a function longest<I>(iter: I) -> usize that returns the length of the longest string in an iterator. It must accept Vec<String>::into_iter() and ["a", "bcd"].iter() (which yields &&str) without conversion. Which bound on I::Item do you need?
Show answer
Require that the item can be viewed as a string slice: where I: Iterator, I::Item: AsRef<str>. The body is iter.map(|s| s.as_ref().len()).max().unwrap_or(0). String implements AsRef<str>, and so does &&str, because AsRef is implemented for references to types that implement it. An equality constraint such as Item = String would reject the second input.
Exercise
A trait declares type Id: Copy + Eq;. Your impl sets type Id = String;. At which point does the compiler report the error, and how does declaring the bound in the trait change what a generic function fn find<T: Lookup>(t: &T, id: T::Id) may do with id?
Show answer
The error appears at the impl, because String does not implement Copy. Because the bounds are declared in the trait, find may copy id and compare it with == without adding T::Id: Copy + Eq to its own where clause.