1- # Iterator::find
1+ # Searching through iterators
22
3- ` Iterator::find ` is a function which when passed an iterator, will return
4- the first element which satisfies the predicate as an ` Option ` . Its
5- signature:
3+ ` Iterator::find ` is a function which iterates over an iterator and searches for the
4+ first value which satisfies some condition. If none of the values satisfy the
5+ condition, it returns ` None ` . Its signature:
66
77``` rust,ignore
88pub trait Iterator {
@@ -29,9 +29,11 @@ fn main() {
2929 // `into_iter()` for vecs yields `i32`.
3030 let mut into_iter = vec2.into_iter();
3131
32- // A reference to what is yielded is `&&i32`. Destructure to `i32`.
32+ // `iter()` for vecs yields `&i32`, and we want to reference one of its
33+ // items, so we have to destructure `&&i32` to `i32`
3334 println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2));
34- // A reference to what is yielded is `&i32`. Destructure to `i32`.
35+ // `into_iter()` for vecs yields `i32`, and we want to reference one of
36+ // its items, so we have to destructure `&i32` to `i32`
3537 println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2));
3638
3739 let array1 = [1, 2, 3];
@@ -44,8 +46,33 @@ fn main() {
4446}
4547```
4648
49+ ` Iterator::find ` gives you a reference to the item. But if you want the _ index_ of the
50+ item, use ` Iterator::position ` .
51+
52+ ``` rust,editable
53+ fn main() {
54+ let vec = vec![1, 9, 3, 3, 13, 2];
55+
56+ let index_of_first_even_number = vec.iter().position(|x| x % 2 == 0);
57+ assert_eq!(index_of_first_even_number, Some(5));
58+
59+
60+ let index_of_first_negative_number = vec.iter().position(|x| x < &0);
61+ assert_eq!(index_of_first_negative_number, None);
62+ }
63+ ```
64+
4765### See also:
4866
4967[ ` std::iter::Iterator::find ` ] [ find ]
5068
69+ [ ` std::iter::Iterator::find_map ` ] [ find_map ]
70+
71+ [ ` std::iter::Iterator::position ` ] [ position ]
72+
73+ [ ` std::iter::Iterator::rposition ` ] [ rposition ]
74+
5175[ find ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find
76+ [ find_map ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map
77+ [ position ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position
78+ [ rposition ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rposition
0 commit comments