Iterator::any

Iterator::any is a function which when passed an iterator, will return
true if any element satisfies the predicate. Otherwise false. Its
signature:

  1. pub trait Iterator {
  2. // The type being iterated over.
  3. type Item;
  4. // `any` takes `&mut self` meaning the caller may be borrowed
  5. // and modified, but not consumed.
  6. fn any<F>(&mut self, f: F) -> bool where
  7. // `FnMut` meaning any captured variable may at most be
  8. // modified, not consumed. `Self::Item` states it takes
  9. // arguments to the closure by value.
  10. F: FnMut(Self::Item) -> bool {}
  11. }
  1. fn main() {
  2. let vec1 = vec![1, 2, 3];
  3. let vec2 = vec![4, 5, 6];
  4. // `iter()` for vecs yields `&i32`. Destructure to `i32`.
  5. println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
  6. // `into_iter()` for vecs yields `i32`. No destructuring required.
  7. println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
  8. let array1 = [1, 2, 3];
  9. let array2 = [4, 5, 6];
  10. // `iter()` for arrays yields `&i32`.
  11. println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
  12. // `into_iter()` for arrays unusually yields `&i32`.
  13. println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2));
  14. }

See also:

std::iter::Iterator::any