--- title: filter_map() in Rust visibility: public glu: - bash - bash run.sh --- One of the things that was really nice to discover in the Rust iterator trait was the `filter_map()` method. It really simplifies a lot of common situations where you are creating optional items and immediately want to filter out the `None`s. ```rust // main.rs fn main() { let original = vec![1, 2, 0, 3]; let filter_mapped: Vec<_> = original .iter() .filter_map(|n| 360_i32.checked_div(*n)) .collect(); let longhand: Vec<_> = original .iter() .map(|n| 360_i32.checked_div(*n)) .filter(|n| n.is_some()) .map(|n| n.unwrap()) .collect(); // Should produce same results, but we got the first one // with much nicer ergonomics. Isn't that nice? println!("filter_mapped: {:?}", filter_mapped); println!("longhand: {:?}", longhand); } ``` ### And to compile and run this example: ```bash # run.sh rustc main.rs && ./main ```