std-method

Iterator::filter_map

Transform a value and optionally emit it in one step. Use parse().ok() only when ignoring invalid inputs is an intentional policy. Expected stdout (not executed): [8, 12] Common mistake: Silently discarding failures that should be reported.

Formal Syntax & Structure

rust syntaxrust
fn filter_map<B, F: FnMut(Self::Item) -> Option<B>>(self, f: F) -> FilterMap<Self, F> where Self: Sized

Working Example

Example Snippetrust
fn main() {    let readings: Vec<u32> = ["8", "missing", "12"].into_iter().filter_map(|s| s.parse().ok()).collect();    println!("{readings:?}");}
Rust Reference