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
Itemis the associated type each step yields.nextreturnsNoneonce the sequence is finished.map,takeandcollectcome along for free.
Keywords and builtins used here
FibItemIteratorOptionSomeVecfnforimplletmainmutnextselfstructtypeu64
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.
Step 3 of 3 in Dynamic dispatch, step 18 of 19 in Traits & generics.