Iterators

any() and all()

The .any() and .all() consumer methods test a boolean predicate FnMut(Self::Item) -> bool across elements of an iterator (&mut self) with short-circuit evaluation.

Signatures and Short-Circuit Behavior

fn any<F>(&mut self, f: F) -> bool
where
    Self: Sized,
    F: FnMut(Self::Item) -> bool;

fn all<F>(&mut self, f: F) -> bool
where
    Self: Sized,
    F: FnMut(Self::Item) -> bool;

Unlike .filter() and .find(), which pass &Self::Item to their closure, .any() and .all() consume each inspected element and pass Self::Item by value to the predicate.

Method Logical Quantifier Short-Circuits When... Result on Empty Iterator
.any(f) Existential ($\exists$, OR) First item returns true (returns true immediately) false
.all(f) Universal ($\forall$, AND) First item returns false (returns false immediately) true (vacuous truth)
fn main() {
    let scores = [85, 92, 78, 99, 64];
    let empty: [i32; 0] = [];

    println!("Any >= 95?       {}", scores.iter().any(|&s| s >= 95));
    println!("All >= 70?       {}", scores.iter().all(|&s| s >= 70));
    println!("Empty .any():    {}", empty.iter().any(|&s| s > 0));
    println!("Empty .all():    {}", empty.iter().all(|&s| s > 0));
}
Any >= 95?       true
All >= 70?       false
Empty .any():    false
Empty .all():    true

Resuming an Iterator After Short-Circuiting

Because .any() and .all() take &mut self, they only consume elements up to and including the element that triggered the short-circuit. Any remaining elements stay in the iterator:

fn main() {
    let mut stream = [2, 4, 7, 8, 10].into_iter();

    // Stops as soon as it sees `7`:
    let has_odd = stream.any(|n| n % 2 != 0);
    let remaining: Vec<i32> = stream.collect();

    println!("Has odd:   {has_odd}");
    println!("Remaining: {remaining:?}");
}
Has odd:   true
Remaining: [8, 10]