Sub topic 4
Associated types you already use: Iterator and Add
You have used associated types every time you wrote a for loop or added two values with +. This chapter looks at the two most common ones, Iterator::Item and Add::Output. It shows how to read their signatures, bound them in your own functions, and avoid the errors they usually cause.
It assumes you can write and implement a trait, use generic functions with trait bounds, and use iterators with for loops and adapters like map. The earlier chapters on declaring associated types and constraining them with bounds are also assumed.
Iterator: one trait, one chosen type
The standard library defines Iterator roughly like this. The real trait has many more provided methods.
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}An implementer must supply two things: the type Item and the next method. Every other iterator method, such as map, filter, sum and collect, has a default body written in terms of next and Self::Item.
Here is a small iterator that counts down to 1.
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, which is 3 + 2 + 1.
The bound I: Iterator<Item = u32> has two parts. I: Iterator says that I is an iterator. Item = u32 says that the type it yields must be exactly u32. Without the second part, the compiler would not know what iter.sum() adds up, and u32 would not be a valid return type.
Why Item is associated, not a parameter
A type that implements Iterator has one natural answer to "what do you yield?". Countdown yields u32 and nothing else. Making Item an associated type enforces this. A type can implement Iterator only once, so Item is fixed for that type.
The same type can yield different things under different names, because Rust has several iterator types for one collection.
| Expression | Iterator type | `Item` |
|---|---|---|
| `vec.iter()` | `std::slice::Iter<'_, T>` | `&T` |
| `vec.iter_mut()` | `std::slice::IterMut<'_, T>` | `&mut T` |
| `vec.into_iter()` | `std::vec::IntoIter<T>` | `T` |
| `"abc".chars()` | `std::str::Chars<'_>` | `char` |
| `1..=3` | `RangeInclusive<i32>` | `i32` |
Each row is a different type with its own single Item. This is why code that is generic over iterators can write I::Item and rely on it naming exactly one type.
Bounding Item with a where clause
Sometimes you do not want one exact type. You want any iterator whose items have some capability. Put the bound on I::Item in a where clause.
use std::fmt::Display;
fn print_all<I>(iter: I)
where
I: Iterator,
I::Item: Display,
{
for x in iter {
println!("{x}");
}
}
fn main() {
print_all(1..=3);
print_all(vec!["a", "b"].into_iter());
}This accepts a range of integers and a vector iterator of &str, because both item types implement Display. It would reject an iterator over a type with no Display implementation.
Use Item = T when you need one exact type. Use I::Item: Bound when any type with a capability will do.
Add: a generic parameter and an associated type together
Add shows a trait that uses both mechanisms side by side. This is its definition.
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}Rhs is the right-hand side type. It is a generic parameter with a default of Self, so impl Add for Point means impl Add<Point> for Point. Output is an associated type, and it is the result of the addition.
Here is the implementation for a Point and a generic function that uses it.
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 }.
Two parts of double matter:
Add<Output = T>says that adding twoTvalues produces anotherT. Without it,value + valuehas the type<T as Add>::Output, which the compiler cannot assume equalsT.Copyis needed becauseaddtakesselfby value. The expressionvalue + valueusesvaluetwice.
Why the split? Rhs varies, Output follows
Whether a trait uses a parameter or an associated type depends on whether a type can have several implementations. A type can add more than one right-hand side type, so Rhs is a parameter. Once the compiler knows both the left type and the Rhs, the result type is determined, so Output is associated.
The following example gives Point two Add implementations.
use std::ops::Add;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Add<Point> for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point { x: self.x + other.x, y: self.y + other.y }
}
}
impl Add<i32> for Point {
type Output = Point;
fn add(self, shift: i32) -> Point {
Point { x: self.x + shift, y: self.y + shift }
}
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p + Point { x: 10, y: 10 });
println!("{:?}", p + 5_i32);
}The output is:
Point { x: 11, y: 12 }
Point { x: 6, y: 7 }The two impls can coexist because they differ in Rhs. If Output were a second parameter, the compiler would have to be told the result type at every use. It would also allow implementations that differ only in Output, which would make p + q ambiguous.
Output does not have to equal the input type. In the standard library, subtracting two Instant values gives a Duration. That is Sub<Instant> for Instant with type Output = Duration.
Common errors
Forgetting Output = T
Consider this function.
use std::ops::Add;
fn double<T: Add + Copy>(value: T) -> T {
value + value
}It does not compile. The compiler reports a mismatched type: it expected T but found the associated type <T as Add>::Output. The bound only says that T can be added. It says nothing about what you get back. Write T: Add<Output = T>.
If the return type should differ, return the associated type itself instead.
use std::ops::Add;
fn double_any<T: Add + Copy>(value: T) -> <T as Add>::Output {
value + value
}
fn main() {
println!("{}", double_any(21));
}This prints 42. The path <T as Add>::Output is covered in the section on qualified paths.
Passing &u32 where Item = u32 is required
Calling sum_all(v.iter()) on a Vec<u32> fails, because v.iter() has Item = &u32. The bound Item = u32 is an exact match, and a reference is a different type. Convert the items first.
fn sum_all<I>(iter: I) -> u32
where
I: Iterator<Item = u32>,
{
iter.sum()
}
fn main() {
let v: Vec<u32> = vec![1, 2, 3];
println!("{}", sum_all(v.iter().copied()));
println!("{}", sum_all(v.into_iter()));
}Both calls print 6. copied() turns an iterator over &u32 into one over u32. Use cloned() for types that are Clone but not Copy.
Implementing Iterator twice
You might want Countdown to yield u32 in one context and String in another. The compiler rejects a second impl Iterator for Countdown with a conflicting implementations error. This is intended. If you need a second item type, create a second type, for example a wrapper struct that holds a Countdown and implements Iterator with type Item = String. You can also build it by calling .map(...) on the first iterator.
Bounding the wrong thing
I: Iterator<Item: Display> is accepted on current compilers, but where I::Item: Display works everywhere and reads clearly. If you see an error such as "the trait bound <I as Iterator>::Item: Display is not satisfied", the bound on Item is missing. Add it to the where clause.
Summary
Iteratorhas one associated type,Item. A type implements it once, so each iterator type has one item type. Bound it exactly withIterator<Item = T>or by capability withI::Item: Trait.Add<Rhs>has a generic parameter for the right-hand side and an associatedOutputfor the result. SeveralRhstypes can coexist for one left type. AddAdd<Output = T>when generic code needs the result to beT.- Most associated-type errors come from forgetting to name the associated type in the bound, or from mixing
Tand&T.
Exercise
This function should return the sum of the doubled items of any iterator over a type T, but it fails to compile. What two bounds does it need, and why? fn sum_doubled<I, T>(iter: I) -> T where I: Iterator<Item = T>, { iter.map(|x| x + x).fold(todo!(), |acc, y| acc + y) }
Show answer
T needs Add<Output = T> and Copy. The closure uses x twice (x + x), so T must be Copy because add takes self by value. The result of x + x has the type <T as Add>::Output, so Output = T is needed to keep it as T for the fold. The fold also needs a starting value, so a bound such as T: Default (or T: From<u8>) is needed to build the zero. Without Output = T, the compiler reports that it found <T as Add>::Output where it expected T.
Exercise
Given let v: Vec<String> = vec!["a".tostring()];, why does printall(v.iter()) from this chapter compile, but a function with the bound I: Iterator<Item = String> reject v.iter()?
Show answer
v.iter() has Item = &String. printall only requires I::Item: Display, and &String implements Display, so it is accepted. The bound Item = String requires the exact type String, and &String is a different type. Pass v.intoiter() (Item = String) or v.iter().cloned() to satisfy it.