Iterators

You can implement the Iterator trait on your own types:

  1. struct Fibonacci {
  2. curr: u32,
  3. next: u32,
  4. }
  5. impl Iterator for Fibonacci {
  6. type Item = u32;
  7. fn next(&mut self) -> Option<Self::Item> {
  8. let new_next = self.curr + self.next;
  9. self.curr = self.next;
  10. self.next = new_next;
  11. Some(self.curr)
  12. }
  13. }
  14. fn main() {
  15. let fib = Fibonacci { curr: 0, next: 1 };
  16. for (i, n) in fib.enumerate().take(5) {
  17. println!("fib({i}): {n}");
  18. }
  19. }
  • IntoIterator is the trait that makes for loops work. It is implemented by collection types such as Vec<T> and references to them such as &Vec<T> and &[T]. Ranges also implement it.
  • The Iterator trait implements many common functional programming operations over collections (e.g. map, filter, reduce, etc). This is the trait where you can find all the documentation about them. In Rust these functions should produce the code as efficient as equivalent imperative implementations.