Sub topic 7
The Iterator trait
This chapter assumes you know ownership and borrowing, generics and trait bounds, Option, and basic Vec use. It also assumes you know closures from the previous chapters.
What the trait requires
An iterator is any type that implements the Iterator trait. The trait has one required associated type and one required method:
type Itemis the type of the values the iterator produces.fn next(&mut self) -> Option<Self::Item>returnsSome(item)while values remain andNoneonce the sequence is finished.
Everything else you use on iterators, such as map, filter and sum, is a provided method built on next. You implement one method and get the rest for free.
Calling next by hand
next takes &mut self because producing a value changes the iterator's internal position. That is why the binding below must be mut.
fn main() {
let v = vec![10, 20];
let mut it = v.iter();
println!("{:?}", it.next()); // Some(10)
println!("{:?}", it.next()); // Some(20)
println!("{:?}", it.next()); // None
println!("{:?}", it.next()); // None
}Here Item is &i32, because v.iter() yields references into the vector. Debug formatting prints a reference to 10 the same way as 10.
What a for loop does
A for loop is a loop over next. The compiler turns the value after in into an iterator with IntoIterator, then calls next until it sees None. The loop below does the same work as for x in v:
fn main() {
let v = vec![1, 2, 3];
let mut it = v.into_iter();
while let Some(x) = it.next() {
println!("{}", x);
}
}The next chapter covers the three ways to get an iterator from a collection: iter, iter_mut and into_iter.
Item determines what you can do
The Item type flows through every later step in a chain. If Item is &i32, a closure passed to map receives a &i32. If Item is i32, it receives an i32. Many type errors in iterator code come from a mismatch between what you assumed Item was and what it actually is.
fn main() {
let v = vec![1, 2, 3];
let by_ref: Vec<&i32> = v.iter().collect();
let by_val: Vec<i32> = v.into_iter().collect();
println!("{:?} {:?}", by_ref, by_val);
}This does not compile as written: v.into_iter() moves v while by_ref still borrows it. To fix it, drop by_ref before the move or print it first. Treat this as an example of how Item and ownership are linked.
Common errors
| Symptom | Cause |
|---|---|
| "cannot borrow `it` as mutable" | The iterator binding was declared without `mut`, but `next` needs `&mut self`. |
| "expected `i32`, found `&i32`" | `Item` is a reference, and the code treats it as a value. Dereference with `*x` or use `.copied()`. |
| Calling `next` after `None` gives surprising results | The basic trait does not guarantee what happens after the first `None`. Most standard iterators keep returning `None`. |
Exercise
In let mut it = vec![5, 6].into_iter();, what is the type of Item, and what does the third call to it.next() return?
Show answer
Item is i32, because into_iter on a Vec<i32> yields owned values. The vector has two elements, so the first two calls return Some(5) and Some(6), and the third call returns None.