liveBook · Manning

Filter_map

As explained in Learn Rust in a Month of Lunches

filter_map is a Rust iterator adaptor that applies a function to each item and yields the values from results that are Some, discarding None results.

filter_map is a Rust iterator adaptor that filters and transforms items in one step. Its closure returns an Option<T>: Some(value) contributes value to the output, while None is discarded. section 9.1.1

Keep values that parse successfully

A useful pattern is input.iter().filter_map(|input| input.parse::<f32>().ok()).collect::<Vec<f32>>(). Each successful parse becomes Some(number), while a failed parse becomes None and disappears. The .ok() method converts Result<T, E> into Option<T>, preserving Ok values but dropping error information. section 9.1.1

Select available company CEOs

A Company can store its CEO as Option<String>. Calling company.get_ceo() inside filter_map keeps names wrapped in Some and skips companies whose CEO is None, producing ["Unknown", "Brendan McCracken"]. section 9.1.1

fn main() {
let user_input = vec![
        "8.9",
        "Nine point nine five",
        "8.0",
        "7.6",
        "eleventy-twelve",
    ];
 
    let successful_numbers = user_input
        .iter()
        .filter_map(|input| input.parse::<f32>().ok())
        .collect::<Vec<f32>>();
 
    println!("{:?}", successful_numbers);
}

Use the runnable parsing example to see filter_map retain valid numeric input while ignoring strings that cannot be parsed. section 9.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the Option-based closure contract and demonstrates collection, but defers deeper iterator implementation details.
Examples
Uses month filtering, optional company CEOs, and string-to-f32 parsing to show discarded None results and retained Some values.
What it assumes
Assumes basic iterators and closures while introducing Option and Result conversion through concrete examples.
What you can do after
Apply filter_map to retain successfully transformed iterator items and collect them into a vector.
How it connects
Connects filter_map with iterators, closures, filter, map, collect, Option, Result, and and_then.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.