Skip to content
Theory · Closures and iterators · lesson 5 of 7

Iterators and for

Picture a conveyor belt in a warehouse. Boxes ride along it one after another, and at the end of the belt a worker takes them off one at a time. The worker does not need to see the whole warehouse at once: they take the next box until the belt is empty.

An iterator is a value that hands out items one at a time, like that belt. You have already met an iterator without calling it one: s.chars() from the theme on strings hands out a string's characters one at a time.

Here the belt picture stops being accurate. A real belt moves by itself. An iterator does nothing on its own: the next item appears only when someone asks for it.

The next method

Asking for the next item means calling the next method. Let's see what it returns:

Rust
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
}

Let's go line by line:

  1. v.iter() creates an iterator over the vector v. The vector itself stays where it is.
  2. The first it.next() returns Some(10): the first item, wrapped in an Option.
  3. The second call returns Some(20).
  4. The items have run out, and the third call returns None.

An iterator remembers where it stopped, and each call of next moves it one step. Since a call changes the iterator, the variable needs mut.

All of this is described by the Iterator trait from the standard library. It asks a type for one method: next. The trait gives the iterator's other methods by default, and all of them work through this next.

The for loop inside

A for loop is calls of next until None comes. On each step the loop takes the value out of Some and puts it into the loop variable. When None comes, the loop ends. That is why for works with any iterator, not only with ranges and vectors.

Three ways to walk a collection

A vector has three methods that create an iterator. They differ in what they hand out.

iter: references

v.iter() hands out shared references &T. You can read the items, and the vector stays with its owner. It is the same as for x in &v, which you know from the theme on collections.

iter_mut: mutable references

v.iter_mut() hands out mutable references &mut T. Through *x you can change an item right inside the vector. It is the same as for x in &mut v.

Rust
fn main() {
    let mut v = vec![1, 2, 3];
    let mut total = 0;
    for x in v.iter() {
        total += x;
    }
    println!("{total}"); // 6
    for x in v.iter_mut() {
        *x *= 10;
    }
    println!("{v:?}"); // [10, 20, 30]
}

The first loop only reads the items through references and adds them up: the result is 6. No star is needed here: += can add a number behind a &i32 reference. The second loop gets mutable references and multiplies each item in place through *x *= 10.

into_iter: the values themselves

v.into_iter() hands out the items themselves, of type T. The vector moves into the iterator, and you can no longer use it after that. This is exactly what for x in v without & does.

Rust
fn main() {
    let names = vec![String::from("Ann"), String::from("Bob")];
    let mut kept = Vec::new();
    for name in names.into_iter() {
        kept.push(name);
    }
    println!("{kept:?}"); // ["Ann", "Bob"]
}

Each string passes from names to kept without copying: the loop gets the String itself, not a reference to it. After the loop names is no longer available.

What iter, iter_mut and into_iter hand out is a classic interview question. Remember the triple: &T, &mut T and T.

Common mistake

The iterator was stored in a variable without mut, and then next was called:

Rust
fn main() {
    let v = vec![10, 20];
    let it = v.iter();
    println!("{:?}", it.next()); // ✗
}
TEXT
error[E0596]: cannot borrow `it` as mutable, as it is not declared as mutable

The program does not compile. next moves the iterator forward, that is, it changes it, so you need let mut it = v.iter();. The vector v does not need mut: the iterator changes, not the vector.

Key points

  • An iterator hands out items one at a time: next returns Some(item), and None at the end.
  • next changes the iterator, so the variable holding it needs mut, or you get error E0596.
  • A for loop calls next until None comes.
  • iter hands out &T, iter_mut hands out &mut T, into_iter hands out T and takes the collection.