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;
5. // `find` takes `&mut self` meaning the caller may be borrowed
6. // and modified, but not consumed.
7. fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
8. // `FnMut` meaning any captured variable may at most be
9. // modified, not consumed. `&Self::Item` states it takes
10. // arguments to the closure by reference.
11. P: FnMut(&Self::Item) -> bool {}
12. }
1. fn main() {
2. let vec1 = vec![1, 2, 3];
3. let vec2 = vec![4, 5, 6];
5. // `iter()` for vecs yields `&i32`.
6. let mut iter = vec1.iter();
7. // `into_iter()` for vecs yields `i32`.
8. let mut into_iter = vec2.into_iter();
10. // A reference to what is yielded is `&&i32`. Destructure to `i32`.
11. println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2));
12. // A reference to what is yielded is `&i32`. Destructure to `i32`.
13. println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2));
15. let array1 = [1, 2, 3];
16. let array2 = [4, 5, 6];
18. // `iter()` for arrays yields `&i32`
19. println!("Find 2 in array1: {:?}", array1.iter() .find(|&&x| x == 2));
20. // `into_iter()` for arrays unusually yields `&i32`
21. println!("Find 2 in array2: {:?}", array2.into_iter().find(|&&x| x == 2));
22. }
