std-method
Iterator::take_while — stop at a boundary
Yield a prefix while the predicate accepts each item. The first rejected item is pulled from the source and not yielded. Expected stdout (not executed): [2, 4] Some(6) Common mistake: Expecting later matching items to be included like filter.
Formal Syntax & Structure
rust syntaxrust
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> boolWorking Example
Example Snippetrust
fn main() { let mut source = [2, 4, 9, 6].into_iter(); let prefix: Vec<_> = source.by_ref().take_while(|n| *n < 5).collect(); println!("{prefix:?} {:?}", source.next());}