typestar

Implementing Iterator in Rust

One next method and every adapter in the standard library works on your type.

struct Fib {
    a: u64,
    b: u64,
}

impl Iterator for Fib {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        let current = self.a;
        self.a = self.b;
        self.b = current + self.b;
        Some(current)
    }
}

fn main() {
    let fib = Fib { a: 0, b: 1 };
    let first: Vec<u64> = fib.take(8).collect();
    println!("{:?}", first);

    let even_sum: u64 = Fib { a: 0, b: 1 }
        .take_while(|n| *n < 100)
        .filter(|n| n % 2 == 0)
        .sum();
    println!("{even_sum}");
}

How it works

  1. Item is the associated type each step yields.
  2. next returns None once the sequence is finished.
  3. map, take and collect come along for free.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
430
Tokens
165
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 3 of 3 in Dynamic dispatch, step 18 of 19 in Traits & generics.

← Previous Next →