rust / intermediate
Snippet
Iterator Chains with Closures
Rust iterators are lazy — they do nothing until consumed. Methods like filter, map, and take are adaptors that transform iterators without executing. The collect method consumes the iterator and produces a collection. This functional style enables clean, composable data transformations with zero runtime overhead compared to imperative loops.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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).collect();println!("{:?}", result); // [4, 16, 36, 64, 100]// Method chaining with multiple operationslet sum = numbers.iter().filter(|&&x| x > 5).take(3).sum::<i32>();println!("Sum: {}", sum); // 6 + 7 + 8 = 21}
Breakdown
1
.iter()
Creates iterator borrowing elements, leaving Vec untouched
2
.filter(|&&x| x % 2 == 0)
Closure takes reference to each element, returns true to keep
3
.map(|x| x * x)
Transforms each element, squaring the value
4
.collect()
Consumes iterator and builds collection, inferring Vec<i32> type
5
.take(3)
Limits iterator to first 3 elements after filtering