Sub topic 2
The Future trait: a value that may not be ready yet
This chapter assumes you know traits, generics, associated types, and enums. You should also have written simple async fn code and called .await.
What a future is
A future is a value that stands for a result that may not exist yet. The standard library models it with the Future trait. Here is a copy of its shape, renamed so it does not clash with the real one:
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>;
}The trait has one associated type and one method:
Outputis the type of the value the future produces when it finishes.pollasks the future to make progress. It returnsPoll::Ready(value)if the work is done, orPoll::Pendingif it is not.
The Pin<&mut Self> receiver and the Context argument are covered in later chapters. For now, read poll as "try to finish, and tell me whether you did."
Futures do nothing until polled
Calling an async fn does not run its body. It builds a future and returns it. Work happens only when something calls poll, and .await does that for you.
use std::future::Future;
async fn add(a: u32, b: u32) -> u32 {
a + b
}
fn assert_future<F: Future<Output = u32>>(_: &F) {}
fn main() {
let fut = add(1, 2);
assert_future(&fut);
// `fut` has not run `a + b` yet. Nothing has polled it.
}The check compiles because add(1, 2) has an anonymous type that implements Future<Output = u32>. Futures are lazy, unlike a thread you spawn, which starts running immediately.
A future's lifecycle
A future may return Pending many times. It returns Ready once. The Future contract says you must not poll it again after that. It may panic, block forever, or misbehave.
Common errors
- Forgetting to await.
let x = add(1, 2);gives you a future, not au32. Usingxas a number is a type error. If you drop the future unused, the compiler warns that futures do nothing unless polled. - Assuming the work started. Creating a future for a network request does not send the request. Only polling does.
- Polling after completion. Executors avoid this by discarding a future once it is ready. Hand-written code must do the same.
Exercise
You write let f = fetch_user(42); where fetch_user is an async fn that sends an HTTP request, and you never .await or poll f. Is the request sent? What is the type of f?
Show answer
No, the request is not sent. Calling an async fn only builds a future, and its body runs only when the future is polled. f is an anonymous compiler-generated type that implements Future with Output equal to the function's return type.