capypad
0 day streak
rust / intermediate
Snippet

Functional Iterator Adapters

Iterators in Rust are lazy and powerful. 'filter' and 'map' allow for functional-style data transformation without unnecessary intermediate allocations.

snippet.rs
rust
1
2
3
4
5
let numbers = vec![1, 2, 3, 4, 5];
let doubled_evens: Vec<i32> = numbers.iter()
.filter(|&x| x % 2 == 0)
.map(|x| x * 2)
.collect();
Breakdown
1
.filter(|&x| x % 2 == 0)
Keeps only the elements that satisfy the condition (even numbers).
2
.collect()
Transforms the iterator back into a collection like a Vec.