]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/fn/closures/closure_examples/iter_any.md
New upstream version 1.62.1+dfsg1
[rustc.git] / src / doc / rust-by-example / src / fn / closures / closure_examples / iter_any.md
CommitLineData
2c00a5a8
XL
1# Iterator::any
2
3`Iterator::any` is a function which when passed an iterator, will return
4`true` if any element satisfies the predicate. Otherwise `false`. Its
5signature:
6
7```rust,ignore
8pub trait Iterator {
9 // The type being iterated over.
10 type Item;
11
12 // `any` takes `&mut self` meaning the caller may be borrowed
13 // and modified, but not consumed.
14 fn any<F>(&mut self, f: F) -> bool where
15 // `FnMut` meaning any captured variable may at most be
16 // modified, not consumed. `Self::Item` states it takes
17 // arguments to the closure by value.
18 F: FnMut(Self::Item) -> bool {}
19}
20```
21
22```rust,editable
23fn main() {
24 let vec1 = vec![1, 2, 3];
25 let vec2 = vec![4, 5, 6];
26
27 // `iter()` for vecs yields `&i32`. Destructure to `i32`.
28 println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
29 // `into_iter()` for vecs yields `i32`. No destructuring required.
30 println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
31
32 let array1 = [1, 2, 3];
33 let array2 = [4, 5, 6];
34
35 // `iter()` for arrays yields `&i32`.
36 println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
5e7ed085 37 // `into_iter()` for arrays yields `i32`.
04454e1e 38 println!("2 in array2: {}", array2.into_iter().any(|x| x == 2));
2c00a5a8
XL
39}
40```
41
42### See also:
43
44[`std::iter::Iterator::any`][any]
45
46[any]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.any