Sub topic 1
Recap: async functions return lazy futures
This chapter reviews the model behind every later chapter. Async closures and async methods in traits are both ways to produce futures, and the rules for what a future holds and when it runs come from the behavior of plain async fn. If this recap feels easy, the next chapters will go quickly. If something here is new, slow down, because the borrowing problems in later chapters follow from it.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Rust ownership and borrowing code, including references with lifetimes such as
&'a str. - Use
async fnand.awaitat a basic level, and know that aFutureis something you poll until it is ready. - Define traits with generics and trait bounds, such as
F: Fn(u32) -> u32. - Use closures and know the difference between
Fn,FnMut, andFnOnce.
The examples need no external crates. They use a tiny executor written with the standard library, so you can compile and run each one with Rust 1.85 or newer.
A future is a value, not a running task
An async fn does not run when you call it. Calling it builds a value that implements Future and returns that value immediately. None of the function body has executed yet. The body runs only when something polls the future, and .await is the usual way to do that.
To observe this, we need something that polls. This small block_on polls one future in a loop until it finishes. It is only suitable for futures that never wait on I/O. A real program would use an executor such as Tokio.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
async fn greet(name: &str) -> String {
println!("running greet");
format!("hello {name}")
}
fn main() {
let fut = greet("ada");
println!("created the future");
let message = block_on(fut);
println!("{message}");
}The output is:
created the future
running greet
hello adaThe line running greet appears after created the future. Creating the future did no work. The work happened inside block_on, when the future was first polled.
Why laziness matters for ordering
Because creation and execution are separate, the order in which you create futures says nothing about the order in which they run. Execution order follows the order in which they are polled.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
async fn step(label: &str) -> usize {
println!("start {label}");
label.len()
}
fn main() {
let a = step("a");
let b = step("bb");
println!("both created");
let total = block_on(async {
let y = b.await;
let x = a.await;
x + y
});
println!("total {total}");
}The output is:
both created
start bb
start a
total 3Future a was created first, but it ran second, because the async block awaited b first. If you forget to await a future at all, its body never runs. The compiler warns about this with the message "futures do nothing unless you .await or poll them".
The lifecycle of a future
A future moves through a small number of states. It starts out unstarted, then runs until it hits an .await that is not ready. At that point it suspends and returns Poll::Pending. It resumes on the next poll, and it finishes with Poll::Ready.
Polling a future again after it has completed is a bug. Most compiler-generated futures panic if you do it. Use .await, which consumes the future, and you will not run into this.
What the compiler builds
An async fn is roughly sugar for a normal function that returns impl Future. The following two signatures are close in meaning:
async fn greet(name: &str) -> String {
format!("hello {name}")
}
// Roughly equivalent signature:
fn greet_desugared<'a>(name: &'a str) -> impl std::future::Future<Output = String> + 'a {
async move { format!("hello {name}") }
}Two details in the desugared form matter for this tutorial.
- The return type is an anonymous type. You cannot write its name. You can only say "some type that implements
Future<Output = String>". That is why generic code takes a type parameter for it, as inFut: Future<Output = u32>. - The future captures its arguments, including borrowed ones. The
'aon the returnedimpl Futureties the future's lifetime to the referencename. The future can be no longer-lived than the data it borrows.
Internally the compiler turns the function body into a state machine. Every local variable that is alive across an .await becomes a field of that state machine, together with the function's arguments. This has three consequences:
- Arguments are moved into the future when you call the function. An owned
Stringargument becomes owned by the future. A&strargument becomes a borrow stored inside the future. - The size of the future is the size of everything it must remember across its suspension points.
- Properties such as
Sendcome from the fields. The future isSendonly if everything held across an.awaitisSend.
Borrowing through a future
Since a future stores its borrowed arguments, the borrow lasts as long as the future exists, not just as long as the call. This is one of the most common sources of confusing errors.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
async fn length(text: &str) -> usize {
text.len()
}
fn main() {
let owned = String::from("borrowed by a future");
let fut = length(&owned);
// `owned` is still borrowed here, because `fut` holds the reference.
let n = block_on(fut);
println!("{n}");
}This compiles because owned outlives fut. If you built fut inside an inner block that ended and dropped owned, the compiler would reject it with "owned does not live long enough". The error appears even though the function body has not run yet, because the future already holds the reference.
The borrow checker treats the future like any struct that holds a reference. This is the key idea to carry forward. The previous example involves one future and one borrow. Later chapters deal with a closure that must create a new future on every call, where each future may need to borrow from the closure's arguments or from the closure itself.
Holding values across an await and `Send`
Whether a future is Send depends on the types held across .await points. Multithreaded executors usually require Send futures, so this matters in practice. A value that is dropped before the next .await does not count.
use std::rc::Rc;
fn assert_send<T: Send>(_: &T) {}
async fn noop() {}
async fn scoped_rc() {
{
let r = Rc::new(5);
println!("{r}");
}
noop().await;
}
fn main() {
assert_send(&scoped_rc());
}This compiles because the Rc is dropped at the end of the inner block, before the .await. If you moved the noop().await line inside the block, so the Rc lived across it, the assert_send call would fail with an error that the future "cannot be sent between threads safely". The error message names the Rc and points at the .await where it is held.
The same reasoning applies later when a trait method returns a future, and the caller needs to know that future is Send.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Nothing prints, no side effect happens | The future was created but never awaited or polled | Add `.await`, or hand the future to an executor |
| Warning: "futures do nothing unless you `.await` or poll them" | A future value was dropped unused | Same as above |
| "does not live long enough" on an argument | The future holds a borrow that outlives the data | Keep the data alive until the future finishes, or pass an owned value |
| "future cannot be sent between threads safely" | A non-`Send` value such as `Rc` is held across an `.await` | Drop it before the `.await`, or use `Arc` |
| Work runs in a different order than expected | Futures run when polled, not when created | Await in the order you want, or use a join combinator |
What to take into the next chapters
The next chapter reviews closures. After that, the tutorial combines the two ideas, a closure that returns a future, and shows where borrowing breaks down. Keep these four facts in mind:
- Calling an
async fnproduces a future and runs none of its body. - The future stores its arguments and any locals held across an
.await. - A borrowed argument makes the future borrow too, so the future cannot outlive that data.
- The returned future type is anonymous, so generic code names it through a type parameter or an
impl Futurebound.
Exercise
The code below prints a single line. What does it print, and why does the body of work not print anything?
async fn work() {
println!("working");
}
fn main() {
let _fut = work();
println!("done");
}
Show answer
It prints only done. Calling work() builds a future but runs none of its body. The future is stored in _fut and never polled or awaited, so working is never printed. The future is dropped unstarted at the end of main.
Exercise
An async fn takes text: &str and awaits another function before using text. Why can you not return that future from a function that created the String that text borrows from?
Show answer
The future stores the &str reference as one of its fields, so it borrows from the String. When the creating function returns, the String is dropped, and the returned future would hold a dangling reference. The borrow checker rejects this because the future's lifetime is tied to the lifetime of text. The fix is to pass an owned String into the async function, or to return the data instead of the future.
Exercise
In what situation is an async fn future not Send, even though all of its arguments are Send?
Show answer
When the body holds a non-Send local, such as an Rc or a MutexGuard from std::sync, across an .await. The compiler stores that local in the future's state machine, so the whole future becomes non-Send. Dropping the value before the .await, for example by ending its scope, removes the problem.