May 2019
Intermediate to advanced
698 pages
17h 21m
English
To understand iterators more thoroughly, we'll implement an iterator that generates prime numbers up to a certain limit that's customizable by the user. First, let's clarify the API expectations that we'll need from our iterator:
// custom_iterator.rsuse std::usize;struct Primes { limit: usize}fn main() { let primes = Primes::new(100); for i in primes.iter() { println!("{}", i); }}
So, we have a type called Primes that we can instantiate with the new method, providing the upper bound on the number of primes to generate. We can call iter() on this instance to convert it in to an iterator type, which can then be used in a for loop. With that said, let's add the new and iter methods on it:
// custom_iterator.rs ...
Read now
Unlock full access