Sub topic 7
The Iterator trait
This chapter assumes you know ownership and borrowing, basic generics and trait bounds, Option, and how to use Vec and slices. It covers the one trait that every iterator chain in Rust rests on. Later chapters cover the individual variants (iter, iter_mut, into_iter), the adapters, and the consumers.
What the trait looks like
An iterator is any type that implements std::iter::Iterator. Here is the trait with the provided methods left out:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// ...dozens of provided methods: map, filter, sum, collect, ...
}The trait has two required pieces.
type Itemis an associated type. It names the type of value the iterator produces.nexthands out the next value, orNonewhen there are no more.
Every other method on Iterator has a default body written in terms of next. That is why a type with only these two pieces gets map, filter, sum and the rest for free.
The trait uses an associated type, not a generic parameter such as Iterator<T>. A given type can implement Iterator only once, so a type has exactly one Item. When you write a bound, you therefore write Iterator<Item = u32>, not Iterator<u32>.
Calling next by hand
You can call next yourself. Each call returns Some(value) while values remain and None after the last one:
fn main() {
let v = vec![10, 20, 30];
let mut it = v.iter();
println!("{:?}", it.next()); // Some(10)
println!("{:?}", it.next()); // Some(20)
println!("{:?}", it.next()); // Some(30)
println!("{:?}", it.next()); // None
}Two details are easy to miss.
- The binding must be
let mut it.nexttakes&mut selfbecause the iterator stores its position, and each call changes it. Withoutmut, the compiler reportscannot borrow it as mutable, as it is not declared as mutable. - The values are
&i32, noti32, becausev.iter()borrows the elements. Debug formatting prints a reference the same way as the value it points to, so the output looks like plain numbers.
What a for loop does
A for loop is a convenience wrapper around this protocol. It does two things:
- It calls
IntoIterator::into_iteron the expression afterin. - It calls
nextin a loop untilNone.
This loop and the for loop version behave the same:
fn main() {
let words = vec!["a", "b", "c"];
// Roughly what `for w in &words { println!("{}", w); }` expands to
let mut iter = IntoIterator::into_iter(&words);
loop {
match iter.next() {
Some(w) => println!("{}", w),
None => break,
}
}
}IntoIterator is a separate trait with one job: converting a value into an iterator. Every Iterator implements IntoIterator by returning itself. That is why you can write for x in some_iterator as well as for x in some_vec. The next chapter covers how &v, &mut v and v each produce a different kind of iterator.
Iterators hold state
Because next mutates the iterator, a half-used iterator is a different value from a fresh one. You can pull a few items, stop, and continue later. The method by_ref lends the iterator out as &mut, so an adapter does not consume it:
fn main() {
let mut it = 1..=6;
let first: Vec<i32> = it.by_ref().take(2).collect();
let rest: Vec<i32> = it.collect();
println!("{:?}", first); // [1, 2]
println!("{:?}", rest); // [3, 4, 5, 6]
}This works because &mut I is itself an iterator whenever I is. Without by_ref(), take(2) would take ownership of it, and the later it.collect() would fail with a "use of moved value" error.
What happens after None
The trait only promises that next returns None when iteration is finished. It does not promise that every later call also returns None. A type may return Some again after a None. Most standard iterators never do, but a custom one can:
struct Flaky {
calls: u32,
}
impl Iterator for Flaky {
type Item = u32;
fn next(&mut self) -> Option<u32> {
self.calls += 1;
if self.calls % 2 == 0 {
None
} else {
Some(self.calls)
}
}
}
fn main() {
let mut f = Flaky { calls: 0 };
println!("{:?}", f.next()); // Some(1)
println!("{:?}", f.next()); // None
println!("{:?}", f.next()); // Some(3)
let mut g = Flaky { calls: 0 }.fuse();
println!("{:?}", g.next()); // Some(1)
println!("{:?}", g.next()); // None
println!("{:?}", g.next()); // None, fuse stops for good
}The adapter fuse() wraps any iterator so that it returns None forever after its first None. Reach for it when you call next again after exhaustion and the source may not be well behaved. Ordinary for loops stop at the first None, so they are never affected.
Provided methods and size_hint
Most of the 70-odd methods on Iterator are provided methods built on next. One of them, size_hint, is worth knowing even if you rarely call it:
fn main() {
let v = vec![1, 2, 3, 4, 5];
let plain = v.iter();
let filtered = v.iter().filter(|x| **x > 2);
println!("{:?}", plain.size_hint()); // (5, Some(5))
println!("{:?}", filtered.size_hint()); // (0, Some(5))
}size_hint returns a pair (lower, upper). The lower bound is the minimum number of items still to come. The upper bound is Some(max) or None if unknown. filter cannot know how many items will pass, so its lower bound is 0. Consumers such as collect use the hint to reserve capacity ahead of time. If you implement Iterator yourself, the default hint is (0, None), which is always correct. An override must never be wrong, because a wrong hint can mislead other code, though it does not cause memory unsafety.
Writing functions over iterators
Two bounds cover most generic code. The right choice depends on what the caller already has.
| Bound | Accepts | Typical use |
|---|---|---|
| `I: Iterator<Item = T>` | Values that are already iterators | Helper that sits at the end of a chain |
| `I: IntoIterator<Item = T>` | Collections, ranges, and iterators | Public APIs that should take a `Vec`, a slice reference, or a chain |
IntoIterator is the more flexible bound for parameters:
use std::fmt::Display;
fn join_all<I>(items: I) -> String
where
I: IntoIterator,
I::Item: Display,
{
let mut out = String::new();
for item in items {
if !out.is_empty() {
out.push_str(", ");
}
out.push_str(&item.to_string());
}
out
}
fn main() {
println!("{}", join_all(vec![1, 2, 3])); // 1, 2, 3
println!("{}", join_all(["x", "y"].iter())); // x, y
println!("{}", join_all((1..4).map(|n| n * n))); // 1, 4, 9
}The same function accepts an owned Vec, a slice iterator, and a mapped range. When a function returns an iterator, use impl Iterator<Item = T> in the return type. The caller then sees an iterator without the long concrete type name.
Common errors
- Forgetting
mut. Callingnext, or any consuming loop on a stored iterator, needs a mutable binding. Chains that you write inline do not need one, because the temporary is owned by the expression. - Using an iterator after it was consumed. Methods that take
selfby value, such assum,collect, andcount, move the iterator. Using it afterwards produces "borrow of moved value". Callby_ref()first, or build a new iterator. - Confusing
Itemwith the element type. Forv.iter()overVec<i32>,Itemis&i32. Code that expectsi32fails with a type mismatch. Dereference with*x, or use a method that yields owned values. - Writing
Iterator<T>. The parameter is an associated type, so the syntax isIterator<Item = T>. - Calling
nexton a collection. AVecis not an iterator.v.next()does not compile. Callv.iter()first.
Exercise
A function receives let it = vec![1, 2, 3].into_iter(); and tries it.next(). The compiler rejects it. What is the one-word fix, and why does the original fail?
Show answer
Add mut: let mut it = .... The method next takes &mut self because the iterator updates its stored position on every call, so the binding must be mutable.
Exercise
You write let first: Vec<i32> = it.take(2).collect(); let rest: Vec<i32> = it.collect(); with it = 1..=6. Why does the second line not compile, and how do you fix the first line so that rest is [3, 4, 5, 6]?
Show answer
take(2) takes it by value, so it is moved and cannot be used again. Change the first line to it.by_ref().take(2).collect(). That lends &mut it, so the iterator keeps its position and it is still usable afterwards.
Exercise
What is the difference between I: Iterator<Item = u8> and I: IntoIterator<Item = u8> as a parameter bound, and which accepts vec![1u8, 2, 3] directly?
Show answer
The Iterator bound requires a value that already is an iterator, so a Vec<u8> is rejected. The IntoIterator bound also accepts anything convertible into an iterator, so vec![1u8, 2, 3] works. Every iterator is also IntoIterator, so IntoIterator is the more flexible bound for parameters.