Iterator::find

Iterator::find 是一个函数,在处理一个迭代器(iterator)时,将返回第一个满足条件的元素作为一个 Option 类型。它的原型如下:

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

参见:

std::iter::Iterator::find