Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator any, all, find and position

Reference for searching Rust iterators: any, all, find, find_map, position and rposition, short-circuiting rules, empty-iterator results and borrowing.

These adapters answer questions about an iterator without collecting it. any asks whether at least one item matches, all asks whether every item matches, find returns the first matching item, and position returns the index of the first match.

They all stop as soon as the answer is known, which makes them safe on infinite iterators as long as a match eventually appears. They take &mut self, so the iterator can be reused afterwards and continues after the item that ended the search.

Rust
let v = [3, 8, 11];
let has_even = v.iter().any(|&n| n % 2 == 0);   // true
let first_big = v.iter().find(|&&n| n > 5);      // Some(8)
let at = v.iter().position(|&n| n == 11);        // Some(2)

Try it

Rust Testing and finding

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 Short-circuiting and reuse

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 any<F: FnMut(Self::Item) -> bool>(&mut self, f: F) -> bool;
fn all<F: FnMut(Self::Item) -> bool>(&mut self, f: F) -> bool;
fn find<P: FnMut(&Self::Item) -> bool>(&mut self, predicate: P) -> Option<Self::Item>;
fn find_map<B, F: FnMut(Self::Item) -> Option<B>>(&mut self, f: F) -> Option<B>;
fn position<P: FnMut(Self::Item) -> bool>(&mut self, predicate: P) -> Option<usize>;
fn rposition<P: FnMut(Self::Item) -> bool>(&mut self, predicate: P) -> Option<usize>
    where Self: ExactSizeIterator + DoubleEndedIterator;
Name Description
f / predicate Closure that tests an item and returns bool (or Option<B> for find_map).

Returns: bool for any and all; Option<Item> for find; Option<B> for find_map; Option<usize> for the position methods.

Errors / panics / edge cases: none of them panic on their own. On an infinite iterator with no match they never return. find uses a different closure shape from any and position: it receives &Item, the others receive Item.

Usage notes

  • Empty iterators: any is false and all is true (vacuous truth); find and position return None.
  • Closure argument types differ. v.iter().any(|&n| ...) takes &i32 by value as a pattern, while v.iter().find(|&&n| ...) needs two & because find passes a reference to the &i32 item. Using .copied() first removes the noise.
  • Resumable: because the methods borrow the iterator mutably, anything after the match is still available. Stateful closures see only the items actually tested.
  • position counts items consumed, so after skip or filter it reports the index within the adapted iterator, not within the original data.
  • rposition searches from the back and requires an ExactSizeIterator; the index it returns still counts from the front.
  • For slices and strings, prefer purpose-built methods when they exist: slice.contains(&x), str::contains, str::find, slice.binary_search for sorted data.
  • Complexity: O(n) worst case, O(1) memory. These are a better choice than filter(..).count() > 0, which never stops early.