Rust Iterators
Iterators
An iterator gives you the items of a collection, like a vector, one at a time.
You have already used iterators: every time you loop through a vector with for, Rust uses an iterator for you.
Iterators also have useful methods that let you change, filter and add up items with very little code.
The iter() Method
Call iter() on a vector to get an iterator. Each call to next() returns the next item, wrapped in Some. When there are no more items, next() returns None:
Example
let fruits = vec!["apple", "banana", "cherry"];
let mut items = fruits.iter();
println!("{:?}", items.next());
println!("{:?}", items.next());
println!("{:?}", items.next());
println!("{:?}", items.next());
Try it Yourself »
next() returns an Option, because there might not be a next item. The iterator must be mut, because it changes each time it moves to the next item.
Loop with an Iterator
A for loop calls next() for you, until it gets None. The enumerate() method adds an index number to each item:
Example
let players = vec!["John", "Liam", "Jenny"];
for (index, player) in players.iter().enumerate() {
println!("{}: {}", index, player);
}
Try it Yourself »
enumerate() gives you pairs of (index, item). The loop unpacks each pair into two variables, just like a tuple.
Change Items with map()
map() uses a closure to change each item. Then collect() gathers the results into a new vector:
Example
let prices = vec![10, 20, 30];
let doubled: Vec<i32> = prices.iter().map(|x| x * 2).collect();
println!("{:?}", doubled);
Try it Yourself »
The original prices vector does not change.
collect() Needs a Type
collect() can create many kinds of collections, so you must tell Rust which one you want. If you forget the type, you get an error:
Example
let prices = vec![10, 20, 30];
let doubled = prices.iter().map(|x| x * 2).collect(); // Error
println!("{:?}", doubled);
Try it Yourself »
Fix it by writing the type after the variable name: let doubled: Vec<i32>.
Keep Some Items with filter()
filter() keeps only the items where the closure returns true:
Example
let numbers = vec![1, 2, 3, 4, 5, 6];
for n in numbers.iter().filter(|x| *x % 2 == 0) {
println!("{}", n);
}
Try it Yourself »
Just like retain() in the Closures chapter, filter() gives the closure a reference to each item, so we write *x. The for loop then prints the items that are left.
Sum and Count
sum() adds all the items together, and count() returns how many items there are:
Example
let scores = vec![50, 75, 100];
let total: i32 = scores.iter().sum();
let count = scores.iter().count();
println!("Total: {}", total);
println!("Count: {}", count);
Try it Yourself »
Just like collect(), sum() needs to know the type of the result, so we write total: i32.
Note: map() and filter() do nothing on their own. They only run when something asks for the items, like collect(), sum() or a for loop.
Common Iterator Methods
| Method | Description |
|---|---|
iter() | Creates an iterator that borrows each item |
next() | Returns the next item in Some, or None when there are no more items |
enumerate() | Adds an index number to each item |
map() | Changes each item with a closure |
filter() | Keeps only the items where the closure returns true |
collect() | Gathers the items into a collection, like a Vec |
sum() | Adds all the items together |
count() | Returns the number of items |