Chapter 2. Basic Async Rust

This chapter introduces the important components of using async in Rust and gives an overview of tasks, futures, async, and await. We cover context, pins, polling, and closures—important concepts for fully taking advantage of async programming in Rust. We have chosen the examples in this chapter to demonstrate the learning points; they may not necessarily be optimal for efficiency. The chapter concludes with an example of building an async audit logger for a sensitive program, pulling all the concepts together.

By the end of this chapter, you will be able to define a task and a future. You’ll also understand the more technical components of a future, including context and pins.

Understanding Tasks

In asynchronous programming, a task represents an asynchronous operation. The task-based asynchronous pattern (TAP) provides an abstraction over asynchronous code. You write code as a sequence of statements. You can read that code as though each statement completes before the next begins. For instance, let’s think about making a cup of coffee and toast, which requires the following steps:

  1. Put bread in toaster

  2. Butter toasted bread

  3. Boil water in kettle

  4. Pour milk

  5. Put in instant coffee granules (not the best, but simplifies the example)

  6. Pour boiled water

We can definitely apply async programming to speed this up, but first we need to break down all the steps into two big steps, make coffee and make toast, as follows:

  1. Make coffee

    1. Boil water in ...

Get Async Rust 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.