liveBook · Manning

Filtering

As explained in Learn Rust in a Month of Lunches

Filtering is the iterator operation of retaining only items that satisfy a condition.

Filtering keeps only iterator items that satisfy a condition. The condition is usually a closure returning bool, while filter_map combines filtering with mapping. section 9.0 section 9.1.1

fn main() {
    let months = vec!["January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November",
    "December"];
 
    let filtered_months = months
        .into_iter()
        .filter(|month| month.len() < 5)       #1
        .filter(|month| month.contains("u"))   #2
        .collect::<Vec<&str>>();
 
    println!("{:?}", filtered_months);
}
#1 For some reason, we don’t want months more than 5 bytes in length. We know that each letter is 1 byte, so using .len() is fine.
#2 Also, we only like months with the letter u. You can .filter() and .filter() again as many times as you like.

Follow the months example to see two filters applied in sequence: one checks length, and the next checks for the letter u. section 9.1.1

Choose the method that matches what the closure should produce:

  • Use filter() when the closure returns bool and you want to retain matching items. section 9.1.1
  • Chain filter() calls when several conditions should narrow the iterator. section 9.1.1
  • Use filter_map() when the closure returns Option<T>; Some values continue and None values disappear. section 9.1.1
  • Call ok() when a Result should become an Option before filter_map(), keeping successful values while discarding errors. section 9.1.1

Filtering usable values

Given user input such as "8.9", "Nine point nine five", and "8.0", iter().filter_map(|input| input.parse::<f32>().ok()) collects only successfully parsed numbers. section 9.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines filter(), chained conditions, filter_map(), and Result-to-Option conversion through focused examples.
Examples
Uses month selection, optional company CEOs, and numeric string parsing as concrete filtering examples.
What it assumes
Assumes basic Rust iterators and closures while teaching boolean conditions, Option values, and Result conversion through examples.
What you can do after
Apply it via Rust's filter(), filter_map(), ok(), and collect() methods to build selected iterator results.
How it connects
Connects filtering with iterators, closures, mapping, Option, Result, and collect().

Also explained in

Compare how 33 books explain filtering →

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.