Sub topic 8
iter, iter_mut and into_iter
This chapter assumes you know ownership and borrowing, generics and trait bounds, and how to use Vec and slices. It also assumes you have seen the Iterator trait and its next method.
Three ways to walk a collection
A collection such as Vec<T> offers three ways to get an iterator. They differ in what they do to the collection and in the type of item they yield.
| Method | Borrows the collection | Item type | Collection usable afterward |
|---|---|---|---|
| `iter()` | Shared borrow | `&T` | Yes |
| `iter_mut()` | Mutable borrow | `&mut T` | Yes, after the iterator is dropped |
| `into_iter()` | Takes ownership | `T` | No, it is moved |
fn main() {
let mut v = vec![1, 2, 3];
for x in v.iter() {
println!("read {}", x); // x: &i32
}
for x in v.iter_mut() {
*x += 10; // x: &mut i32, so dereference to write
}
let doubled: Vec<i32> = v.into_iter().map(|x| x * 2).collect();
println!("{:?}", doubled); // [22, 24, 26]
// println!("{:?}", v); // error: v was moved by into_iter
}After into_iter(), v no longer exists. Each element is moved out of the vector and handed to the iterator by value.
What a for loop calls
A for loop does not call iter() directly. It calls IntoIterator::into_iter on the expression after in. Vec<T> implements IntoIterator three times, and the type of that expression picks which implementation runs.
fn main() {
let mut names = vec![String::from("a"), String::from("b")];
for n in &names { // same as names.iter(), n: &String
println!("{}", n);
}
for n in &mut names { // same as names.iter_mut(), n: &mut String
n.push('!');
}
for n in names { // same as names.into_iter(), n: String
println!("{}", n);
}
}Reference items in closures
Because iter() yields &T, closures in a pipeline receive references. filter adds one more level, because its closure takes &Item. On iter(), that makes &&T.
fn main() {
let v = vec![1, 2, 3, 4];
let evens: Vec<i32> = v
.iter()
.filter(|x| **x % 2 == 0) // x: &&i32
.copied() // &i32 -> i32
.collect();
println!("{:?}", evens); // [2, 4]
}Use copied() for Copy types and cloned() for types that implement Clone. Either one turns borrowed items into owned ones without consuming the original vector.
Common errors
- Using a collection after
into_iter()or afor x in vloop. The compiler reports "borrow of moved value". Iterate over&vor callv.iter()if you needvafterward. - Holding
iter()while mutating the collection. The shared borrow lasts as long as the iterator, sov.push(...)inside the loop does not compile. - Forgetting to dereference. With
iter_mut(), write*x += 1, notx += 1.
Exercise
Given let v = vec![String::from("x"), String::from("y")];, which call lets you build a Vec<String> of uppercase copies and still use v afterward: v.iter() or v.into_iter()? What item type does your choice yield?
Show answer
Use v.iter(). It yields &String, so v.iter().map(|s| s.to_uppercase()).collect::<Vec<String>>() creates new strings while v stays valid. into_iter() yields String but moves v.