rust / intermediate
Snippet
Iterator Adaptors and Lazy Evaluation
Rust iterators are lazy, meaning no computation happens until you call a terminal operation like collect(). Each adaptor (filter, map, take) creates a new iterator without executing any code. This enables efficient chaining without intermediate allocations.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn main() {let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];let result: Vec<_> = numbers.iter().filter(|&&x| x % 2 == 0).map(|x| x * x).collect();println!("Original: {:?}", numbers);println!("Filtered & squared evens: {:?}", result);let sum: i32 = numbers.iter().filter(|&&x| x > 5).take(3).sum();println!("Sum of first 3 numbers > 5: {}", sum);}
Breakdown
1
.iter()
Creates a borrowing iterator over the vector
2
.filter(|&&x| x % 2 == 0)
Closure returns true for even numbers; &&x destructures the &&i32 reference
3
.map(|x| x * x)
Transforms each element; lazy until collect() is called
4
.collect()
Terminal operation that consumes the iterator and builds a collection
5
.take(3)
Limits processing to first 3 matching elements