Iterators
Map and Filter
Transforming a Sequence
Iterator adaptors build a pipeline. filter keeps matching items and map transforms them before collect.
Program
Play the program to keep even numbers and scale them.
map_filter.rs
fn main() {
let nums = vec![1, 2, 3, 4, 5];
let doubled_evens: Vec<i32> = nums.iter().filter(|&&n| n % 2 == 0).map(|&n| n * 10).collect();
println!("{doubled_evens:?}");
}
filter
`filter` keeps items where the predicate is true.
map
`map` transforms each remaining item.
collect
`collect` gathers the results into a `Vec`.