liveBook · Manning

Future

As explained in Learn Rust in a Month of Lunches

A Future is a Rust abstraction representing an asynchronous computation whose result may become available later and which can be polled for readiness.

A Future represents a value that may become available later. An `async fn` returns a Future rather than its usable result right away: `async fn give_8() -> u8` returns a Future whose output is a `u8`. The work does not start just because the function was called; you need to await the Future to get its output. section 19.3.1 section 19.4

Polling means checking whether that output is ready. A poll returns `Pending` if it is not ready yet, or `Ready(value)` if it is. Think of it like asking whether something has arrived, then checking again later if it has not. Usually you write `.await` and let an async runtime handle the polling. You do not need to understand `Pin`, which appears in the `Future` trait’s method signature, to start using async Rust. section 19.3.1 section 19.3.2

Getting the value

Given `async fn give_8() -> u8 { 8 }`, calling `give_8()` gives you a Future, not a `u8`. Write `let number = give_8().await;` inside an async function or block to obtain the number. If you try `.await` in an ordinary `main`, the compiler points out that `await` is only allowed in async code. An async runtime, such as Tokio, provides a way to run an async `main`. section 19.3.1 section 19.3.2

Once you have several Futures, choose how to wait for them:

  • Await them one after another when each result should be obtained before starting the next call. section 19.3.4
  • Use Tokio’s `join!` to poll them together and collect their results, or `select!` to take the first result that completes. section 19.3.4
  • Use `try_join!` when the Futures return `Result` values and a failure should produce an error. section 19.3.4

A Future need not produce a quick answer. For example, awaiting an async server’s `.serve()` Future keeps the server running until it shuts down. section 24.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains readiness, polling, awaiting, and the Future trait’s Output type, while deferring a deep understanding of Pin.
Examples
Uses an async function returning a u8, compiler errors around await, and timed Futures combined with Tokio macros.
What it assumes
Introduces Future readiness and polling from simple examples without requiring a deep understanding of Pin.
What you can do after
Apply it via Tokio to await a Future and choose between sequential waits, join!, and select! for multiple Futures.
How it connects
Connects Futures to async functions, polling, async runtimes, Tokio, and concurrent waiting with join! and select!.

Also explained in

Compare how 8 books explain future →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.