Iterators

Iterator trait 用来实现关于集合(collection)类型(比如数组)的迭代器。

这个 trait 只需定义一个指向 next(下一个)元素的方法,这可手动在 impl 代码块中定义,或者自动定义(比如在数组或区间中)。

为方便起见,for 结构通常使用 .into_iterator() 方法将一些集合类型转换为迭代器。

下面例子展示了如何访问使用 Iterator trait 的方法,关于这方面的更多内容可点击这里查看。

1. struct Fibonacci {
2. curr: u32,
3. next: u32,
4. }

6. // 实现关于 `Fibonacci` (斐波那契)的 `Iterator`。
7. // `Iterator` trait 只需定义一个指向 `next`(下一个)元素的方法。
8. impl Iterator for Fibonacci {
9. type Item = u32;

11. // 我们在这里使用 `.curr` 和 `.next` 来定义数列(sequence)。
12. // 返回类型为 `Option<T>`:
13. //     * 当 `Iterator` 结束时,返回 `None`。
14. //     * 其他情况,返回被 `Some` 包裹(wrapped)的下一个值。
15. fn next(&mut self) -> Option<u32> {
16. let new_next = self.curr + self.next;

18. self.curr = self.next;
19. self.next = new_next;

21. // 既然斐波那契数列不存在终点,那么 `Iterator` 将不可能
22. // 返回 `None`,而总是返回 `Some`。
23. Some(self.curr)
24. }
25. }

27. // 返回一个斐波那契数列生成器(generator)
28. fn fibonacci() -> Fibonacci {
29. Fibonacci { curr: 1, next: 1 }
30. }

32. fn main() {
33. // `0..3` 是一个 `Iterator`,会产生:0,1 和 2。
34. let mut sequence = 0..3;

36. println!("Four consecutive `next` calls on 0..3");
37. println!("> {:?}", sequence.next());
38. println!("> {:?}", sequence.next());
39. println!("> {:?}", sequence.next());
40. println!("> {:?}", sequence.next());

42. // `for` 通过 `Iterator` 进行工作,直到 `Iterator` 为 `None`。
43. // 每个 `Some` 值都被解包(unwrap)且限定为一个变量(这里是 `i`)。
44. println!("Iterate through 0..3 using `for`");
45. for i in 0..3 {
46. println!("> {}", i);
47. }

49. // `take(n)` 方法提取 `Iterator` 的前 `n` 项。
50. println!("The first four terms of the Fibonacci sequence are: ");
51. for i in fibonacci().take(4) {
52. println!("> {}", i);
53. }

55. // `skip(n)` 方法通过跳过前 `n` 项缩短了 `Iterator` 。
56. println!("The next four terms of the Fibonacci sequence are: ");
57. for i in fibonacci().skip(4).take(4) {
58. println!("> {}", i);
59. }

61. let array = [1u32, 3, 3, 7];

63. // `iter` 方法对数组/slice 产生一个 `Iterator`。
64. println!("Iterate the following array {:?}", &array);
65. for i in array.iter() {
66. println!("> {}", i);
67. }
68. }