capypad
0 day streak
rust / intermediate
Snippet

Iterator Adaptors and Lazy Evaluation

Rust iterators use lazy evaluation, meaning operations are not executed until consumed by a terminal operation like 'collect', 'sum', or 'for_each'. This allows chaining multiple adaptors like filter, map, skip, and take without intermediate allocations. Iterator adaptors transform the iterator without consuming it, and flat_map can expand each element into multiple values.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result: Vec<i32> = numbers
.iter()
.filter(|&&x| x % 2 == 0)
.map(|x| x * x)
.skip(1)
.take(2)
.collect();
println!("Result: {:?}", result);
let sum_of_squares: i32 = numbers
.iter()
.filter(|&&x| x > 3)
.map(|x| x * x)
.sum();
println!("Sum of squares (x > 3): {}", sum_of_squares);
let chained: Vec<i32> = (1..=5)
.flat_map(|x| std::iter::repeat(x).take(x))
.collect();
println!("FlatMap result: {:?}", chained);
}
Breakdown
1
.iter()
Creates a non-consuming iterator over the vector reference
2
.filter(|&&x| x % 2 == 0)
Predicate closure keeping only even numbers; &&x needed to dereference &&i32
3
.map(|x| x * x)
Transforms each element by squaring it
4
.skip(1).take(2)
Skips first element, then takes next two elements from filtered stream
5
.collect()
Terminal operation consuming iterator and collecting into a Vec
6
.flat_map(|x| std::iter::repeat(x).take(x))
Maps each x to x copies of itself, flattening into single sequence