1
- # Iterator::find
1
+ # Searching through iterators
2
2
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:
6
6
7
7
``` rust,ignore
8
8
pub trait Iterator {
@@ -29,9 +29,11 @@ fn main() {
29
29
// `into_iter()` for vecs yields `i32`.
30
30
let mut into_iter = vec2.into_iter();
31
31
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`
33
34
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`
35
37
println!("Find 2 in vec2: {:?}", into_iter.find(| &x| x == 2));
36
38
37
39
let array1 = [1, 2, 3];
@@ -44,8 +46,28 @@ fn main() {
44
46
}
45
47
```
46
48
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
+
47
65
### See also:
48
66
49
67
[ ` std::iter::Iterator::find ` ] [ find ]
68
+ [ ` std::iter::Iterator::position ` ] [ position ]
50
69
51
70
[ find ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find
71
+ [ find_map ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find_map
72
+ [ position ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position
73
+ [ rposition ] : https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.rposition
0 commit comments