Iterator::find

Iterator::find is a function which when passed an iterator, will return
the first element which satisfies the predicate as an Option. Its
signature:

  1. pub trait Iterator {
  2. // The type being iterated over.
  3. type Item;
  4. // `find` takes `&mut self` meaning the caller may be borrowed
  5. // and modified, but not consumed.
  6. fn find<P>(&mut self, predicate: P) -> Option<Self::Item> 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 reference.
  10. P: 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`.
  5. let mut iter = vec1.iter();
  6. // `into_iter()` for vecs yields `i32`.
  7. let mut into_iter = vec2.into_iter();
  8. // A reference to what is yielded is `&&i32`. Destructure to `i32`.
  9. println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2));
  10. // A reference to what is yielded is `&i32`. Destructure to `i32`.
  11. println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2));
  12. let array1 = [1, 2, 3];
  13. let array2 = [4, 5, 6];
  14. // `iter()` for arrays yields `&i32`
  15. println!("Find 2 in array1: {:?}", array1.iter() .find(|&&x| x == 2));
  16. // `into_iter()` for arrays unusually yields `&i32`
  17. println!("Find 2 in array2: {:?}", array2.into_iter().find(|&&x| x == 2));
  18. }

See also:

std::iter::Iterator::find