Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator take_while, skip_while and map_while

Reference for Iterator::take_while, skip_while and map_while in Rust: stopping or starting at the first item that fails a test, and the item that gets consumed.

These three adapters work on the front of an iterator and decide where to cut by looking at values instead of counting. take_while(p) yields items until the predicate first returns false, then stops for good. skip_while(p) does the opposite: it discards items until the predicate first returns false, then yields everything from there on, including later items that would match again. map_while(f) is take_while and map in one: it yields the Some values returned by the closure and stops at the first None.

All three are "first failure" operations: once the switch flips, the predicate is never called again. That is the difference from filter, which tests every item.

Rust
let small: Vec<i32> = [1, 2, 9, 3].into_iter().take_while(|&n| n < 5).collect();
// [1, 2]  (3 is not reached)

Try it

Rust take_while versus filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust map_while and the consumed item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
    where P: FnMut(&Self::Item) -> bool;

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
    where P: FnMut(&Self::Item) -> bool;

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
    where P: FnMut(Self::Item) -> Option<B>;
Name Description
predicate (take_while, skip_while) Receives a reference to each item. take_while keeps going while it returns true; skip_while drops items while it returns true.
predicate (map_while) Receives each item by value and returns Some(mapped) to continue or None to stop.

Returns: lazy adapters. map_while was stabilized in Rust 1.57; the other two are available since 1.0.

Usage notes

  • take_while consumes the first failing item. When it sees an item that fails the test, that item has already been pulled from the source and is thrown away. If you need it afterwards, use peekable or split a slice with partition_point.
  • After the stop, they are done. take_while remembers that it has finished and does not call the predicate again, even if you keep calling next().
  • skip_while is a one-way gate. Items after the gate opens are passed even if they match the predicate again, unlike filter(|x| !p(x)).
  • Sorted data. On a sorted slice, partition_point (binary search) is faster than take_while(...).count() for finding the cut position.
  • Infinite iterators are the natural partner: (1..).take_while(...), successors(...).take_while(...). Make sure the predicate eventually fails, or the loop never ends.
  • Lengths are unknown, so none of these are ExactSizeIterator, and take_while is not double-ended.
  • map_while and errors. .map_while(Result::ok) yields successes until the first Err, a compact "read until failure" tool for iterators of Result.