Understanding the new Generators

A new feature is coming to Rust in 2018—asynchronous generators. Generators are functions that can yield elements before returning from the function and resume executing later. This is great for the loops that we have seen in this chapter. With generators, we could directly replace many of the callbacks with the new async/await syntax.

This is still an unstable feature that can only be used in nightly, so it may be that the code you write becomes obsolete before stabilization. Let's see a simple example of a generator:

#![feature(generators, generator_trait)]use std::ops::{Generator, GeneratorState};fn main() {    let mut generator = || {        for i in 0..10 {            yield i;        }        return "Finished!";    };    loop { match generator.resume() ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.