8 State machines, coroutines, macros, and preludes
This chapter covers
- Using traits to construct state machines
- Writing pausable functions with coroutines
- Implementing procedural macros
- Providing preludes to improve the usability of your crates
This chapter continues some of the themes from chapter 7 and builds on much of what we’ve learned in the book. We’ll start by discussing state machines and coroutines. Then we’ll introduce procedural macros, an advanced Rust feature that allows us to generate code at compile time. Last, we’ll discuss preludes, which are a commonly used Rust library pattern to improve usability.
Rust’s traits are powerful, and combined with generics, they let us build type-safe abstractions that allow us to guarantee correctness at compile time. This has some fairly significant implications, as we can avoid a host of problems that often plague software. State machines are robust ways to model stateful systems, and as we’ll see in this chapter, it’s surprisingly easy to build type-safe state machines in Rust.
State machines have always interested me, and I’ve used them many times, but I particularly like how easy it is to build a basic state machine in Rust without using additional crates or libraries. When building stateful systems in Rust, I create many small state machines as needed.