Rust 1.99 (2024 edition) reference · Iterators
Rust Iterator::map, filter and filter_map Method
Transform and select items lazily: map each item, keep matching ones, or do both at once with filter_map.
Rust 1.99 (2024 edition)
Syntax
fn map<B, F>(self, f: F) -> Map<Self, F> fn filter<P>(self, p: P) -> Filter<Self, P> fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
Parameters
| Parameter | Description |
|---|---|
map |
Transform each item. |
filter |
Keep items where the closure returns true. |
filter_map |
Map to Option and drop Nones. |
enumerate / zip / rev / take / skip |
Other common adapters. |
Examples
fn main() {
let nums = [1, 2, 3, 4, 5, 6];
let squares_of_even: Vec<i32> = nums.iter().filter(|&&n| n % 2 == 0).map(|n| n * n).collect();
println!("{squares_of_even:?}");
let parsed: Vec<u32> = ["1", "x", "3"].iter().filter_map(|s| s.parse().ok()).collect();
println!("{parsed:?}");
}
Output
[4, 16, 36] [1, 3]
Run this on your computer — see “Get Started” for setup.
fn main() {
let names = ["ana", "ben", "cy"];
let scores = [90, 72, 85];
for (i, (n, s)) in names.iter().zip(scores).enumerate().skip(1) {
println!("{i}: {n} {s}");
}
}
Output
1: ben 72 2: cy 85
Run this on your computer — see “Get Started” for setup.
Related
Iterator::sum, fold, any and max_by_key· Reduce an iterator to one value: totals, counts, custom folds, checks, and minimum or maximum items.Iterator::collect· Turn an iterator into a collection: Vec, String, HashMap, HashSet, or a Result that fails on the first error.- Rust Iterators and Closures · tutorial