Rust Iterators Adapters and Consumers


Example

Iterator methods can be broken into two distinct groups:

Adapters

Adapters take an iterator and return another iterator

//         Iterator  Adapter
//             |       |
let my_map = (1..6).map(|x| x * x);
println!("{:?}", my_map);
Output
Map { iter: 1..6 }

Note that the values were not enumerated, which indicates that iterators are not eagerly evaluated — iterators are "lazy".

Consumers

Consumers take an iterator and return something other than an iterator, consuming the iterator in the process.

//                    Iterator  Adapter       Consumer
//                        |       |              |
let my_squares: Vec<_> = (1..6).map(|x| x * x).collect();
println!("{:?}", my_squares);
Output
[1, 4, 9, 16, 25]

Other examples of consumers include find, fold, and sum.

let my_squared_sum: u32 = (1..6).map(|x| x * x).sum();
println!("{:?}", my_squared_sum);
Output
55