How it works...

A Generator is currently defined as any closure that uses the new yield keyword. When it is executed with .resume() [11], it will run until it hits a yield. If run again, the generator will continue where it left off until it reaches another yield or encounters a return. If there are no more yields left in the generator, it will simply return an empty tuple, behaving as if encountering return ();.

Because there are two scenarios of what a generator does (yield vs return), you have to check the result of .resume() every time you use it, as it could be GeneratorState::Yielded or GeneratorState::Complete.

At the time of writing, you can return a different type than you yield. The situation around this is somewhat unclear, as the reason for this quirk is the aforementioned convention to return (); when running out of yields. Maybe the final version of generators in Rust will not rely on this behavior, and only allow returning the same type as yielding. You can find the discussion about this and more at https://github.com/rust-lang/rust/issues/43122.

Besides async, another big use case for generators is iterators. So much so that the Rust standard library iterators are planned to eventually be rewritten with generators. At the moment, the exact way of how this transition should happen has not been figured out, so there is no generic implementation of Iterator for Generator. To work around this, you can create a little wrapper type like we did with GeneratorIterator[50], which implements Iterator for its wrapped Generator.

We illustrate how to use it by rewriting the Fibonacci iterator from Chapter 2, Working with Collections; Creating an own iterator, with a generator in the fibonacci function [64]. The implementation looks pretty clean, doesn't it? As a reminder, here is how we wrote the original implementation using the Iterator trait directly, which not only needed a function, but also a struct and a trait implementation:

fn fibonacci() -> Fibonacci {
Fibonacci { curr: 0, next: 1 }
}
struct Fibonacci {
curr: u32,
next: u32,
}
impl Iterator for Fibonacci {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let old = self.curr;
self.curr = self.next;
self.next += old;
Some(old)
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.142.2