Iterator::any
Iterator::any 是一个函数,在处理一个迭代器(iterator)时,当其中任一元素符合条件(predicate)时将返回 true,否则返回 false。它的原型如下:
1. pub trait Iterator {
2. // 迭代相关的类型(原文:The type being iterated over)。
3. type Item;
5. // `any` 接受 `&mut self` 作为调用者可能被借用和修改,但不会消费掉。
6. // (原文: `any` takes `&mut self` meaning the caller may be
7. // borrowed and modified, but not consumed.)
8. fn any<F>(&mut self, f: F) -> bool where
9. // `FnMut` 表示任意捕获变量很可能都被修改,而非消费。
10. // `Self::Item` 表明了通过值来接受闭包类型参数。
11. // (原文:`FnMut` meaning any captured variable may at
12. // most be modified, not consumed. `Self::Item` states it
13. // takes arguments to the closure by value.)
14. F: FnMut(Self::Item) -> bool {}
15. }
1. fn main() {
2. let vec1 = vec![1, 2, 3];
3. let vec2 = vec![4, 5, 6];
5. // 对 vec 的 `iter()` 产出 `&i32`(原文:`iter()` for vecs yields
6. // `&i32`)。解构成 `i32` 类型。
7. println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
8. // 对 vec 的 `into_iter()` 产出 `i32` 类型。无需解构。
9. println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
11. let array1 = [1, 2, 3];
12. let array2 = [4, 5, 6];
14. // 对数组(array)的 `iter()` 产出 `&i32`。
15. println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
16. // 对数组的 `into_iter()` 通常产出 `&i32`。
17. println!("2 in array2: {}", array2.into_iter().any(|&x| x == 2));
18. }
