Sub topic 8
iter, iter_mut and into_iter
This chapter assumes you know ownership and borrowing, Vec and slices, and basic generics and trait bounds. You should also have seen the Iterator trait and its next method. Here we look at how a collection becomes an iterator, and why three methods exist for it.
Three ways to start iterating
A Vec<T> can hand out its elements in three ways. Each way gives a different item type, and each leaves the collection in a different state.
| Method | Borrows the collection as | Item type | Collection afterwards |
|---|---|---|---|
| `iter()` | `&self` | `&T` | Still usable, unchanged |
| `iter_mut()` | `&mut self` | `&mut T` | Usable once the iterator is dropped, possibly modified |
| `into_iter()` | `self` | `T` | Moved, no longer usable |
The choice follows the same rules as ordinary borrowing. Reading needs a shared reference. Changing elements in place needs a unique reference. Taking elements out needs ownership.
iter: shared references
iter() borrows the collection immutably. You can have many such iterators at once, and the collection is usable again when they are gone.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
for n in names.iter() {
// n: &String, so nothing is moved or cloned
println!("{} has {} letters", n, n.len());
}
println!("{:?}", names); // still available
}iter_mut: mutable references
iter_mut() yields &mut T. You write through the reference with *. While the iterator is alive, nothing else may read or write the collection.
fn main() {
let mut scores = vec![10, 20, 30];
for s in scores.iter_mut() {
*s += 5;
}
println!("{:?}", scores); // [15, 25, 35]
}The collection must be declared mut. Without that, iter_mut is not callable.
into_iter: ownership
into_iter() takes the collection by value and yields each element by value. This is the only variant that lets you move non-Copy elements out, such as String values, into something else.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
let upper: Vec<String> = names
.into_iter()
.map(|n| n.to_uppercase())
.collect();
println!("{:?}", upper); // ["ADA", "GRACE"]
// println!("{:?}", names); // error: borrow of moved value: `names`
}If you stop partway through an into_iter, the remaining elements are dropped when the iterator is dropped.
What a for loop does
A for loop calls IntoIterator::into_iter on the expression after in. IntoIterator is the trait that turns a value into an iterator. Vec<T> implements it three times, once each for Vec<T>, &Vec<T> and &mut Vec<T>. This is why the three loop forms behave differently:
fn main() {
let mut v = vec![1, 2, 3];
for x in &v {
println!("read {}", x); // x: &i32, same as v.iter()
}
for x in &mut v {
*x *= 2; // x: &mut i32, same as v.iter_mut()
}
for x in v {
println!("owned {}", x); // x: i32, same as v.into_iter()
}
// v has been moved by the last loop
}Every Iterator also implements IntoIterator and returns itself. That is why you can write for x in v.iter().map(...) directly.
Where into_iter changes meaning
The name into_iter hides a subtlety. Its behavior depends on the type it is called on.
- On
Vec<T>, it yieldsT. - On
&Vec<T>or&[T], it yields&T. - On
&mut Vec<T>, it yields&mut T. - On an array
[T; N]in Rust 2021 and later, it yieldsT. In the 2018 edition, the method-call formarray.into_iter()yielded&Tfor compatibility reasons. Check your edition if you see references where you expect values.
So (&v).into_iter() is the same as v.iter(). If a function receives a &Vec<String> and you call into_iter() on it, you get &String, not String. You cannot take ownership through a reference.
Other collections
Maps yield pairs. HashMap<K, V>::iter() yields (&K, &V). iter_mut() yields (&K, &mut V). Keys are never mutable, because changing a key would corrupt the map's internal structure. into_iter() yields (K, V).
use std::collections::HashMap;
fn main() {
let mut stock = HashMap::new();
stock.insert("apple", 3);
for (_name, qty) in stock.iter_mut() {
*qty += 1;
}
for (name, qty) in &stock {
println!("{name}: {qty}"); // apple: 4
}
}Slices and arrays have iter() and iter_mut() too, and Vec gets them through deref to a slice. String has no iter(). You pick a view of it with chars() or bytes().
Item types and closure parameters
The item type decides what your closure receives. This is the most common source of confusing type errors in iterator code. filter passes its closure a reference to each item. With iter(), the item is already &i32, so the closure sees &&i32.
fn main() {
let v = vec![1, 2, 3, 4];
// iter(): items are &i32, filter's closure gets &&i32
let a: Vec<i32> = v.iter().filter(|x| **x % 2 == 0).copied().collect();
// Pattern in the parameter removes the references
let b: Vec<i32> = v.iter().filter(|&&x| x % 2 == 0).copied().collect();
// into_iter() on a clone: items are i32, filter's closure gets &i32
let c: Vec<i32> = v.clone().into_iter().filter(|x| x % 2 == 0).collect();
println!("{:?} {:?} {:?}", a, b, c); // [2, 4] [2, 4] [2, 4]
}Use copied() for Copy types and cloned() for types that implement Clone when you need owned values from an iter(). cloned() allocates for types like String. Prefer to keep working with references until the end of the chain when you can.
Gotchas
Mutating while iterating. While v.iter() is alive, v is borrowed. Calling v.push(...) inside the loop fails with error E0502, "cannot borrow v as mutable because it is also borrowed as immutable". Gather the changes first, then apply them:
fn main() {
let mut v = vec![1, 2, 3];
let extra: Vec<i32> = v
.iter()
.filter(|&&x| x % 2 == 1)
.map(|&x| x * 10)
.collect();
v.extend(extra);
println!("{:?}", v); // [1, 2, 3, 10, 30]
}Lazy iter_mut does nothing alone. v.iter_mut().map(|x| *x += 1); runs no code, because map is lazy until something consumes it. The compiler warns that the iterator is unused. Use a for loop or for_each for side effects.
Using a collection after into_iter. The error is E0382, "borrow of moved value". Iterate by reference with &v or v.iter() if you need the collection afterwards.
Two mutable iterators. You cannot hold two iter_mut() iterators over the same collection. Use split_at_mut or chunks_mut when you need disjoint mutable access.
Exercises
Exercise
Given let mut words = vec![String::from("a"), String::from("bb")];, write a loop that appends "!" to each word in place. Then say which of iter, iter_mut or into_iter you used and why words is still usable afterwards.
Show answer
for w in words.iter_mut() { w.push('!'); } (or for w in &mut words). iter_mut yields &mut String, so push changes each string in place. The loop only borrows words, so the borrow ends with the loop and words holds ["a!", "bb!"].
Exercise
What item type does each call yield, assuming v: Vec<String>? (1) v.iter() (2) v.iter_mut() (3) v.into_iter() (4) (&v).into_iter()
Show answer
(1) &String. (2) &mut String. (3) String, and v is moved. (4) &String, because into_iter on a reference behaves like iter.