liveBook · Manning

Future

As explained in Rust Servers, Services, and Apps

The Rust Future trait defines the interface for an asynchronous computation that can be polled toward completion.

A future represents a deferred asynchronous computation that eventually produces one value. An `async fn` returns something that implements the `Future` trait; `.await` waits for that value. In a server handling concurrent requests, futures let an async runtime schedule other tasks while work is not ready to complete. section 10.3 section 10.0

pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

The trait declares an `Output` type and a `poll` method. The runtime polls through `Pin<&mut Self>` and passes a `Context`; polling returns `Poll<Output>`. section 10.3 section 10.4

A custom future makes the scheduling contract visible:

  • Return `Poll::Pending` when the value is unavailable. The executor can schedule other tasks instead of waiting for this one. section 10.4
  • Arrange for the task’s waker to be notified when progress is possible. The executor can then poll the future again; repeatedly waking an always-pending future merely repeats the poll. section 10.4
  • Return `Poll::Ready(value)` when the computation has its final value. section 10.4

An expiration timer

`AsyncTimer` stores an expiration time. Its `poll` method returns `Poll::Ready(String)` once that time has arrived. Before then, it clones the waker, starts a sleeping thread that will wake the task at expiration, and returns `Poll::Pending`. While the timer is pending, Tokio can run another spawned task. This contrasts with the companion file-read simulation, which calls `std::thread::sleep()` inside its async code. section 10.5 section 10.5

`Pin` is required in the custom `poll` signature because futures may be polled repeatedly; its deeper mechanics are left aside here. Tokio supplies the executor used in these examples, and Actix Web uses Tokio underneath for asynchronous task execution. section 10.4 section 10.3

How Rust Servers, Services, and Apps covers it

How deep it goes
Works through the trait signature, polling, waking, and a custom timer, while leaving Pin’s deeper mechanics aside.
Examples
Uses concurrent file-read simulations and a custom expiration timer to show pending and ready results.
What it assumes
Assumes Rust programming context but introduces the async primitives needed to examine a future’s behavior.
What you can do after
Build it from scratch: implement a timer future that returns pending, wakes its task, and eventually returns a value.
How it connects
Links futures to async/await, Tokio executors, wakers, pinning, and Actix Web.

Also explained in

Compare how 8 books explain future →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Servers, Services, and Apps. The section links point to the parts of the book it draws on.