Sub topic 1
Recap: async functions return lazy futures
Prerequisites
This chapter assumes basic Rust ownership, borrowing, closures, the Future trait, and async/await.
Async functions return lazy futures
An async fn does not run its body when called. It returns a future, which is a value describing work that can be started and resumed later. An executor polls the future until it completes.
async fn add_one(value: u32) -> u32 {
value + 1
}
async fn example() {
let future = add_one(4);
let result = future.await;
assert_eq!(result, 5);
}Calling add_one(4) creates the future. The body runs when future is awaited or otherwise polled. The future can hold local values and borrows until the operation finishes.
Closures and the Fn trait family
A closure is an anonymous function that can capture values from its surrounding scope. Rust classifies closures by how they use those captures:
Fncan be called repeatedly without changing captured state.FnMutcan be called repeatedly while mutating captured state.FnOnceconsumes a captured value and may be called only once.
These traits describe how the closure itself is called. They do not describe whether the result is synchronous or asynchronous.
Closures that return async blocks
Before async closures, the usual pattern was a normal closure returning an async block:
use std::future::Future;
async fn apply<F, Fut>(f: F, value: u32) -> u32
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32>,
{
f(value).await
}
async fn example() {
let result = apply(|x| async move { x + 1 }, 4).await;
assert_eq!(result, 5);
}The extra Fut parameter names the future type produced by the closure.
Where this pattern breaks
The pattern becomes difficult when the returned future must borrow the closure's argument or captured state. The Fn bound describes one output type, but it cannot express that each call returns a future whose lifetime is tied to that call's input borrow.
A captured value can also cause trouble. Moving it into an async move block may consume it, preventing later calls. Borrowing it may require a future lifetime that the older closure signature cannot state.
Exercise
When does the body of an async function begin running?
Show answer
When its returned future is polled, usually through .await.