std-method

Iterator::map_while — transform a valid prefix

Apply a conversion until it returns None. Unlike filter_map, normal collection stops at that point. The adapter is not guaranteed fused; wrap it with fuse if permanent exhaustion is required. Expected stdout (not executed): [5] Common mistake: Using map_while to skip bad records and continue through all later inputs.

Formal Syntax & Structure

rust syntaxrust
fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where Self: Sized, P: FnMut(Self::Item) -> Option<B>

Working Example

Example Snippetrust
fn main() {    let values: Vec<_> = ["5", "bad", "9"].into_iter().map_while(|s| s.parse::<u32>().ok()).collect();    println!("{values:?}");}
Rust Reference