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
