capypad
0 day streak
rust / intermediate
Snippet

Iterator Lazy Evaluation and Chaining

Rust iterators are lazy - they perform no computation until consumed by a terminal operation like collect() or sum(). Each adaptor (filter, map, take) creates a new iterator wrapping the previous one, enabling efficient chaining without intermediate collections.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec<i32> = numbers
.iter()
.filter(|&&x| x > 3)
.map(|x| x * x)
.take(3)
.collect();
println!("{:?}", result); // [16, 25, 36]
let sum: i32 = (0..100)
.filter(|&x| x % 2 == 0)
.map(|x| x * x)
.sum();
println!("Sum of squares of evens: {}", sum); // 171700
}
Breakdown
1
.iter()
Creates an iterator reference - no computation yet
2
.filter(|&&x| x > 3)
Lazy adaptor - only runs when iterator is consumed
3
.take(3)
Limits output to first 3 matching elements, short-circuiting computation
4
.collect()
Terminal operation that triggers all lazy adaptors to execute