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
































