Iterators

The Iterator trait is used to implement iterators over collections such as arrays.

The trait requires only a method to be defined for the next element, which may be manually defined in an impl block or automatically defined (as in arrays and ranges).

As a point of convenience for common situations, the for construct turns some collections into iterators using the .into_iterator() method.

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

6. // Implement `Iterator` for `Fibonacci`.
7. // The `Iterator` trait only requires a method to be defined for the `next` element.
8. impl Iterator for Fibonacci {
9. type Item = u32;

11. // Here, we define the sequence using `.curr` and `.next`.
12. // The return type is `Option<T>`:
13. //     * When the `Iterator` is finished, `None` is returned.
14. //     * Otherwise, the next value is wrapped in `Some` and returned.
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. // Since there's no endpoint to a Fibonacci sequence, the `Iterator`
22. // will never return `None`, and `Some` is always returned.
23. Some(self.curr)
24. }
25. }

27. // Returns a Fibonacci sequence generator
28. fn fibonacci() -> Fibonacci {
29. Fibonacci { curr: 1, next: 1 }
30. }

32. fn main() {
33. // `0..3` is an `Iterator` that generates: 0, 1, and 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` works through an `Iterator` until it returns `None`.
43. // Each `Some` value is unwrapped and bound to a variable (here, `i`).
44. println!("Iterate through 0..3 using `for`");
45. for i in 0..3 {
46. println!("> {}", i);
47. }

49. // The `take(n)` method reduces an `Iterator` to its first `n` terms.
50. println!("The first four terms of the Fibonacci sequence are: ");
51. for i in fibonacci().take(4) {
52. println!("> {}", i);
53. }

55. // The `skip(n)` method shortens an `Iterator` by dropping its first `n` terms.
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. // The `iter` method produces an `Iterator` over an array/slice.
64. println!("Iterate the following array {:?}", &array);
65. for i in array.iter() {
66. println!("> {}", i);
67. }
68. }