Sub topic 2
The Future trait: a value that may not be ready yet
This chapter assumes you know Rust ownership, traits and generics, and enums with pattern matching. It also assumes you have written simple async fn code and called .await. Here you learn what a Future is as a type. The details of polling, wakers and pinning come in the following chapters, so they appear only as far as the trait signature requires.
A value that may not exist yet
A normal function call blocks until the result exists. A Future is a value that stands for a result that will exist later. You can hold it, pass it around, store it in a struct, and ask it whether the result is ready.
The trait lives in std::future:
use std::pin::Pin;
use std::task::{Context, Poll};
trait MyFuture {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
fn main() {}This is a copy of the real trait under another name, so it compiles on its own. The real std::future::Future has the same shape. It has two parts:
type Outputis the type of the final result. AFuture<Output = u32>will eventually produce au32.pollis the only required method. It asks the future to make progress and returns aPoll<Self::Output>, which is eitherPoll::Ready(value)orPoll::Pending.
The self: Pin<&mut Self> receiver and the Context argument look unusual. For now, read them as "the future must stay in place while it is polled" and "here is a way to ask to be called again". Later chapters cover each in turn.
A future is a state, not a running task
The key point is that a future does not run by itself. No thread is working on it in the background. It is a value in memory that holds its current state, and it advances only when someone calls poll on it.
This differs from a thread or from a JavaScript promise, which start working as soon as they are created.
| Concept | Starts work when | Who drives it |
|---|---|---|
| `std::thread::spawn` | Created | The operating system scheduler |
| JavaScript `Promise` | Created | The event loop |
| Rust `Future` | First `poll` | Whoever calls `poll` (usually an executor) |
Rust calls this model lazy. Creating a future is cheap and has no side effects, because none of the function body has run yet.
You can see this directly. The program below creates a future, prints a line, and only then polls it.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
async fn greet() -> &'static str {
println!("body runs");
"hello"
}
fn main() {
let fut = greet();
println!("future created");
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
match fut.as_mut().poll(&mut cx) {
Poll::Ready(v) => println!("ready: {v}"),
Poll::Pending => println!("pending"),
}
}Waker::noop() needs Rust 1.85 or later. It builds a waker that does nothing, which is enough here because greet never waits. The output is:
future created
body runs
ready: hello"body runs" prints after "future created". Calling greet() only built the future. The body ran during the first poll.
The life of a future
A future moves through a small set of states. The caller drives every transition by calling poll.
A future that returns Pending has not failed. It is waiting for something, such as a socket becoming readable or a timer firing. It tells the executor it is waiting, and the executor polls it again later.
Futures are ordinary values
Because a future is just a value of some type, the usual language tools apply to it.
- You can store it in a variable and decide later when to poll it.
- You can move it into another function or a struct field.
- You can drop it. Dropping a future that has not finished abandons its work. A later chapter covers this cancellation behavior.
- Each
asyncblock orasync fncall produces a distinct anonymous type. Two async blocks with identical bodies still have different types.
That last point explains the common signature impl Future<Output = T>. It names the trait without naming the unnameable concrete type:
use std::future::Future;
fn double_later(n: u32) -> impl Future<Output = u32> {
async move { n * 2 }
}
async fn double_later_sugar(n: u32) -> u32 {
n * 2
}
fn main() {
let _a = double_later(2);
let _b = double_later_sugar(2);
}The two functions are equivalent from a caller's point of view. Both return some type that implements Future<Output = u32>. The async fn form is shorthand for the first form. The next chapter explains what the compiler generates behind it.
When the future lives behind a pointer, such as Pin<Box<dyn Future<Output = u32>>>, the concrete type is erased. This lets you keep futures of different types in one collection.
What a future captures
An async block that uses async move takes ownership of the variables it mentions, as a closure does. Without move, it borrows them. The borrow rules then apply for as long as the future exists, and that can be longer than you expect, because the future may sit unpolled for a while.
async fn length(s: &str) -> usize {
s.len()
}
fn main() {
let fut;
{
let text = String::from("short-lived");
// fut = length(&text); // error: `text` does not live long enough
fut = length("static text");
let _ = &text;
}
let _ = fut;
}The commented line fails to compile because the future would hold a reference to text after text is dropped. Passing a &'static str works. A future that borrows is tied to the lifetime of what it borrows, and the compiler enforces this like any other borrow.
Common mistakes
- Creating a future and never polling it. Calling an async function without
.awaitdoes nothing. The compiler warns with "unused implementer ofFuturethat must be used". Treat that warning as an error in practice. - Polling after completion. The trait does not say what happens if you call
pollagain after it returnedReady. Many futures panic. Executors must stop polling a future once it completes. - Assuming progress without polling. Holding a future in a variable while you do other work does not advance it. A timer future may have long expired, yet nothing observes that until someone polls.
- Treating
Pendingas an error.Pendingis a normal answer. A future may return it many times before it returnsReady.
Summary of the model
- A
Futurehas an associatedOutputtype and apollmethod. pollreturnsReady(value)when the result exists andPendingwhen it does not.- A future does nothing until it is polled.
- A future is an ordinary value with its own anonymous type, and it can capture variables by move or by borrow.
Exercise
In the lazy example, suppose you delete the call to fut.as_mut().poll(&mut cx) but keep let fut = greet();. What does the program print, and why?
Show answer
It prints only "future created". Calling greet() builds a future without running the body, so "body runs" never prints. The future is dropped unpolled at the end of main.
Exercise
What is the type of async fn parse(s: &str) -> Result<u32, std::num::ParseIntError> as a function that returns a future, and what is the Output type of that future?
Show answer
It is fn parse(s: &str) -> impl Future<Output = Result<u32, ParseIntError>> + '_, with the future borrowing s. The Output is Result<u32, ParseIntError>. Awaiting the future yields the Result, which you can then handle with ?.