Skip to content
Justice Tech School

Iterators

Iterators are lazy. map, filter, enumerate, zip, take, skip and rev adapt them, and collect, sum, count and fold consume them.

Example
let v = vec![1, 2, 3, 4, 5, 6];
let evens: Vec<i32> = v.iter().filter(|x| *x % 2 == 0).cloned().collect();
let total: i32 = v.iter().map(|x| x * x).sum();
println!("{:?} {}", evens, total);
for (i, x) in v.iter().enumerate().take(2) { print!("{}:{} ", i, x); }
println!();

Result

[2, 4, 6] 91
0:1 1:2 

Exercise

Add up the items.

v.iter().::<i32>()

Quiz Test

When do iterator adapters run?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.