Sub topic 3
Constraining associated types in bounds and where clauses
This chapter assumes you can write a trait with an associated type, as in the previous chapter. It also assumes you know basic generic bounds such as T: Display. Here you will learn two ways to restrict an associated type: fix it to one concrete type, or require it to implement traits.
Fixing the type with `Item = T`
A bound on a trait with an associated type can name that type using Name = Type inside angle brackets. This is called an associated type binding.
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)));
}The program prints 6. sum_all accepts any iterator, but only if its Item is exactly u32. Passing an iterator of i64 is a compile error.
The same constraint works in argument position with impl Trait: fn sum_all(iter: impl Iterator<Item = u32>) -> u32.
Requiring traits with `I::Item: Trait`
Often you do not need one specific type. You need the item to support some behavior. Put a bound on the associated type itself, usually 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"].into_iter());
}I::Item is shorthand for "the Item type of I". The first bound says I is an iterator. The second says its items can be printed. Both calls compile because i32 and &str implement Display.
You can combine the two forms. Here the second iterator must yield the same item type as the first.
fn same_items<A, B>(a: A, b: B) -> bool
where
A: Iterator,
B: Iterator<Item = A::Item>,
A::Item: PartialEq,
{
a.zip(b).all(|(x, y)| x == y)
}
fn main() {
println!("{}", same_items(1..4, vec![1, 2, 3].into_iter()));
println!("{}", same_items(1..4, vec![1, 2, 9].into_iter()));
}This prints true, then false. The binding Item = A::Item links the two type parameters without adding a third one.
Which form to choose
| Need | Bound |
|---|---|
| Exactly one known type | `I: Iterator<Item = u32>` |
| Any type with some behavior | `I::Item: Display` |
| Two types must match | `B: Iterator<Item = A::Item>` |
| Bounds on a type used in the return value | `where` clause, for readability |
Common errors
Leaving out the bound on the associated type is the most frequent mistake. This code does not compile:
fn print_all<I: Iterator>(iter: I) {
for item in iter {
println!("{}", item); // error[E0277]: `<I as Iterator>::Item` doesn't implement `Display`
}
}Bounding I: Iterator says nothing about Item. The compiler knows only that some type exists, so it allows nothing beyond what every type allows. Add I::Item: Display.
Another error is writing Iterator<u32>. That is rejected because Iterator has no generic type parameters. The Item = u32 syntax is the only way to name its associated type.
Bounds in the trait definition
A trait can also demand things of its own associated type. Every implementer must then pick a type that satisfies the bound.
use std::fmt::Debug;
trait Container {
type Item: Debug;
fn first(&self) -> Option<&Self::Item>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T: Debug> Container for Stack<T> {
type Item = T;
fn first(&self) -> Option<&T> {
self.items.first()
}
}
fn main() {
let s = Stack { items: vec![10, 20] };
println!("{:?}", s.first());
}Because the trait declares type Item: Debug, generic code using C: Container can print C::Item without repeating the bound. The impl<T: Debug> is needed because T must satisfy that bound.
Exercise
Write the signature of a function largest that takes any iterator I and returns the largest item as Option<I::Item>. Use a where clause, and require only what Iterator::max needs plus nothing extra.
Show answer
fn largest<I>(iter: I) -> Option<I::Item> where I: Iterator, I::Item: Ord { iter.max() }. Iterator::max requires Self::Item: Ord, so that is the bound to put on I::Item. An equality binding such as Item = u32 would work but would needlessly limit the function to one type.