Sub topic 4
Associated types you already use: Iterator and Add
This chapter assumes you can write a trait and implement it, use generic bounds such as T: Display, and run a for loop over an iterator. You have used associated types every time you called .map() or wrote a + b. Here you will see where they sit in two standard library traits and how to constrain them.
Iterator and its Item type
Iterator declares one associated type, Item, and one required method:
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}Each implementer picks Item once. The compiler then knows exactly what next returns for that type. This example counts down from a number:
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. The bound I: Iterator<Item = u32> has two parts. I: Iterator says the type is an iterator. Item = u32 fixes its associated type. Without the second part, iter.sum() could not promise a u32 result, because I::Item could be any type.
Add: a parameter and an associated type together
Add uses both mechanisms:
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhsis a generic parameter. It is the type on the right of the+. It defaults toSelf.Outputis an associated type. It is the type of the result.
The result type is not always the input type. Adding two Instant values is not defined, but Instant + Duration gives an Instant. Because Output belongs to the implementation, each impl states its own result.
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 }));
}This prints Point { x: 2, y: 4 }. Writing impl Add for Point uses the default Rhs = Point. The Copy bound is needed because value + value consumes value twice.
Comparing the two mechanisms
| Part of the trait | Written as | Who chooses it | How many per type |
|---|---|---|---|
| `Rhs` in `Add` | Generic parameter | The caller or impl, per impl | Many impls for one type |
| `Output` in `Add` | Associated type | The impl, once per impl | One for each `Rhs` |
| `Item` in `Iterator` | Associated type | The impl | Exactly one per type |
A type can implement Iterator only once, so Item is unambiguous. A type can implement Add<Rhs> for several Rhs types, so Rhs must be a parameter. Once Rhs is known, Output follows.
Reading the bound syntax
Iterator<Item = u32>constrains the associated type to one exact type.Iterator<Item: Display>requires only thatItemimplementsDisplay. It uses the sameName: Boundsyntax as a generic parameter.Add<Output = T>mixes with other bounds using+.
When you meet a long standard library signature, look first at which traits are in the bounds. Then check which associated types are pinned with =.
Exercise
Why does sum_all need I: Iterator<Item = u32> and not just I: Iterator? What would iter.sum() be unable to promise?
Show answer
With only I: Iterator, the item type I::Item is unknown, so iter.sum() cannot be known to produce a u32. The Item = u32 constraint fixes the associated type, so the compiler can return a u32.
Exercise
Why is Output an associated type of Add while Rhs is a generic parameter?
Show answer
A type can implement Add for several right-hand types, so Rhs must be a parameter that selects the impl. For a given Self and Rhs, there is exactly one result type, so Output is chosen by the impl as an associated type.