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. }
  5. // Implement `Iterator` for `Fibonacci`.
  6. // The `Iterator` trait only requires a method to be defined for the `next` element.
  7. impl Iterator for Fibonacci {
  8. type Item = u32;
  9. // Here, we define the sequence using `.curr` and `.next`.
  10. // The return type is `Option<T>`:
  11. // * When the `Iterator` is finished, `None` is returned.
  12. // * Otherwise, the next value is wrapped in `Some` and returned.
  13. fn next(&mut self) -> Option<u32> {
  14. let new_next = self.curr + self.next;
  15. self.curr = self.next;
  16. self.next = new_next;
  17. // Since there's no endpoint to a Fibonacci sequence, the `Iterator`
  18. // will never return `None`, and `Some` is always returned.
  19. Some(self.curr)
  20. }
  21. }
  22. // Returns a Fibonacci sequence generator
  23. fn fibonacci() -> Fibonacci {
  24. Fibonacci { curr: 1, next: 1 }
  25. }
  26. fn main() {
  27. // `0..3` is an `Iterator` that generates: 0, 1, and 2.
  28. let mut sequence = 0..3;
  29. println!("Four consecutive `next` calls on 0..3");
  30. println!("> {:?}", sequence.next());
  31. println!("> {:?}", sequence.next());
  32. println!("> {:?}", sequence.next());
  33. println!("> {:?}", sequence.next());
  34. // `for` works through an `Iterator` until it returns `None`.
  35. // Each `Some` value is unwrapped and bound to a variable (here, `i`).
  36. println!("Iterate through 0..3 using `for`");
  37. for i in 0..3 {
  38. println!("> {}", i);
  39. }
  40. // The `take(n)` method reduces an `Iterator` to its first `n` terms.
  41. println!("The first four terms of the Fibonacci sequence are: ");
  42. for i in fibonacci().take(4) {
  43. println!("> {}", i);
  44. }
  45. // The `skip(n)` method shortens an `Iterator` by dropping its first `n` terms.
  46. println!("The next four terms of the Fibonacci sequence are: ");
  47. for i in fibonacci().skip(4).take(4) {
  48. println!("> {}", i);
  49. }
  50. let array = [1u32, 3, 3, 7];
  51. // The `iter` method produces an `Iterator` over an array/slice.
  52. println!("Iterate the following array {:?}", &array);
  53. for i in array.iter() {
  54. println!("> {}", i);
  55. }
  56. }