Iterator::find
Iterator::find 是一个函数,在处理一个迭代器(iterator)时,将返回第一个满足条件的元素作为一个 Option 类型。它的原型如下:
1. pub trait Iterator {
2. // 迭代相关的类型。
3. type Item;
5. // `find` 接受 `&mut self` 作为调用者可能被借用和修改,但不会消费掉。
6. // (原文:`find` takes `&mut self` meaning the caller may be borrowed
7. // and modified, but not consumed.)
8. fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where
9. // `FnMut` 表示任意捕获变量很可能都被修改,而非消费。
10. // `&Self::Item` 表明了通过引用接受闭包类型的参数。
11. // (原文:`FnMut` meaning any captured variable may at most be
12. // modified, not consumed. `&Self::Item` states it takes
13. // arguments to the closure by reference.)
14. P: FnMut(&Self::Item) -> bool {}
15. }
1. fn main() {
2. let vec1 = vec![1, 2, 3];
3. let vec2 = vec![4, 5, 6];
5. // 对 vec 产出 `&i32` 类型。
6. let mut iter = vec1.iter();
7. // 对 vec 产出 `i32` 类型。
8. let mut into_iter = vec2.into_iter();
10. // 产出内容的引用是 `&&i32` 类型。解构成 `i32` 类型。
11. println!("Find 2 in vec1: {:?}", iter .find(|&&x| x == 2));
12. // 产出内容的引用是 `&i32` 类型。解构成 `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()` 产出 `&i32`。
19. println!("Find 2 in array1: {:?}", array1.iter() .find(|&&x| x == 2));
20. // 对数组的 `into_iter()` 通常产出 `&i32``。
21. println!("Find 2 in array2: {:?}", array2.into_iter().find(|&&x| x == 2));
22. }
