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)

Create a free account to save this page, take notes and track your progress. Sign in

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

ParameterDescription
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

Example 1
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.

zip, enumerate and skip
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.

Was this page helpful?