Course contentsShow
← Rust
Lesson 1157 of 1,91010. Concurrency PrimitivesFree lesson

The Anatomy of a Future

You will understand how Rust represents computation that completes at a later time.

In this lesson, you will learn how Rust represents computation that completes at a later time by dissecting the Future trait.

The State Machine Pattern

At its core, a Future is not a thread or a background process; it is a state machine that manages a computation capable of pausing and resuming. In Rust, this is defined by the Future trait, which requires a single method: poll.

Unlike traditional blocking code, where a thread waits for a result, a Future expects to be polled. Think of a Future like a "receipt" for a task you've ordered. When you call poll on that receipt, the task attempts to make progress.

The Anatomy of poll

The signature of poll is the heart of asynchronous Rust:

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
  1. Pin<&mut Self>: This ensures the future is pinned in memory. Because a Future is a state machine generated by the compiler, it often contains internal references (self-referential structs). Pinning guarantees that the memory location of the future won't change while it is being polled, preventing dangling pointers.
  2. Context<'_>: This contains a Waker. If the future cannot finish its work yet (e.g., waiting for data on a socket), it registers this Waker. When the resource finally becomes ready, the system calls the Waker to tell the executor, "Hey, try polling this future again!"
  3. Poll<Self::Output>: This is an enum with two states: Ready(T) or Pending. Pending signals that the computation needs more time.

How it runs

A Future does absolutely nothing until it is polled. It is "lazy." When you call poll, the code inside the future executes until it hits an await point. At that point, it either returns Ready if the data is there, or it saves its current state (the variables currently in scope) into a struct and returns Pending.

By representing computation as a state machine rather than an OS thread, Rust allows thousands of tasks to coexist on a single thread, simply by moving between these "ready" and "pending" states.

Key Takeaway: A Future is a state machine that defers work until explicitly polled, using a Waker to request a wake-up when it is ready to progress.