Sub topic 5
Writing async closures
This chapter covers the syntax and everyday behavior of async closures. It assumes you can write an async fn and .await its result. It also assumes you know how closures capture variables and how Fn, FnMut and FnOnce differ. Async closures are stable since Rust 1.85, so use a toolchain at least that recent.
What an async closure is
An async closure is a closure whose body is an async block. Calling it does not run the body. It returns a future, and the body runs only when you .await that future.
The syntax puts async in front of the parameter list:
async |x| x + 1 // takes x, returns a future
async || { /* ... */ } // no parameters
async move |x| x + 1 // moves captured variables into the closureThe snippets in this chapter each define async fn demo(). To run one, paste it below this small helper. The helper polls a future to completion without an external runtime, which is enough because none of these futures wait on I/O. Waker::noop is stable since Rust 1.85.
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;
}
}
}
fn main() {
block_on(demo());
}
async fn demo() {
let greet = async |name: &str| format!("hello, {name}");
assert_eq!(greet("world").await, "hello, world");
assert_eq!(greet("rust").await, "hello, rust");
}The closure greet can be called many times. Each call creates a new future, and each future runs separately when awaited.
The three call-site forms
The closure itself is a value, and creating it costs nothing beyond capturing variables. Three things happen at different moments:
- Creating the closure captures variables.
- Calling the closure builds a future. No body code runs yet.
- Awaiting the future runs the body to completion and produces the output.
The dotted edge matters. The future produced by an async closure can borrow from the closure's own captured state. That ability is what separates async closures from the older pattern.
How an async closure differs from a closure returning an async block
The classic pattern is |x| async move { ... }. It is an ordinary closure that returns a future, and the two pieces are separate. An async closure is one unit, and the future may refer back to the closure.
| Aspect | `\ | x\ | async move { ... }` | `async \ | x\ | { ... }` |
|---|---|---|---|---|---|---|
| What it is | A normal closure returning a future | A closure whose call returns a future that can borrow from it | ||||
| Bound to accept it | `F: Fn(X) -> Fut, Fut: Future` | `F: AsyncFn(X) -> Out` | ||||
| Future borrows captured state | Not without moving or cloning it | Yes, by shared or mutable reference | ||||
| Borrowed arguments such as `&str` | Hard to express in the bounds | Works with `AsyncFn(&str)` |
The next chapter covers the AsyncFn bounds in detail. Here the focus is on writing the closures themselves.
Capturing variables
Capture rules mirror regular closures. The compiler picks the weakest capture that the body needs. It uses a shared borrow if the body only reads, a mutable borrow if the body mutates, and a move if the body consumes a value. Add move to force every captured variable to be moved in.
Capturing by mutable reference
Here is the case that is awkward with the classic pattern. The closure mutates a captured vector, and each call's future borrows from the closure:
async fn demo() {
let mut log: Vec<String> = Vec::new();
let mut record = async |msg: &str| {
log.push(msg.to_string());
};
record("start").await;
record("end").await;
assert_eq!(log, ["start", "end"]);
}Two details to notice:
- The binding is
let mut record. Calling a closure that mutates its captures needs&mut record, exactly like a regularFnMutclosure. - You can read
logagain only after the last use ofrecord. The closure holds the mutable borrow until then.
Capturing by move
Use async move when the closure must own its data, for example because it outlives the current scope. Inside the closure, the owned values are still used through the closure, so the future can borrow them on each call:
async fn demo() {
let prefix = String::from("user:");
let label = async move |name: &str| format!("{prefix}{name}");
assert_eq!(label("ada").await, "user:ada");
assert_eq!(label("lin").await, "user:lin");
// `prefix` has moved into the closure and can't be used here.
}This closure can be called repeatedly because the body only reads prefix. Each call's future borrows prefix from the closure.
Consuming a capture
If the body moves a captured value out, the closure can only be called once. This is the same rule as FnOnce. The matching bound is AsyncFnOnce:
async fn run_once<F>(f: F) -> String
where
F: AsyncFnOnce() -> String,
{
f().await
}
async fn demo() {
let owned = String::from("moved out");
let result = run_once(async move || owned).await;
assert_eq!(result, "moved out");
}The compiler infers the closure's kind from its body, just as for regular closures. You never write the kind on the closure itself. It shows up only in the bound that accepts it.
Parameters and return types
Parameters work as in normal closures, with optional type annotations. A reference parameter such as name: &str may return a future that uses that borrow. The classic pattern struggles with this, and async closures handle it because the closure is generic over the argument's lifetime.
You can give an explicit return type with ->. This looks the same as for ordinary closures, with the body in braces:
use std::num::ParseIntError;
async fn demo() {
let parse_next = async |s: &str| -> Result<u32, ParseIntError> {
let n: u32 = s.parse()?;
Ok(n + 1)
};
assert_eq!(parse_next("41").await, Ok(42));
assert!(parse_next("x").await.is_err());
}The annotation matters whenever you use ?. Without it, the compiler cannot tell which error type the body's Ok(...) should carry, and it reports a type annotation error. The return type describes the future's output, not the future itself.
Common errors
Most mistakes with async closures fall into a few groups.
- Forgetting
.await. Callingrecord("x");builds a future and drops it. The body never runs. The compiler warns that the future is unused (#[must_use]), so read that warning. - Missing
mut. A closure that mutates a capture needslet mut. The error says that you cannot borrow the closure as mutable. - Two live futures from one mutating closure. Each call borrows the closure mutably for as long as its future lives. Calling the closure a second time before the first future is dropped is a borrow error. Await each future before the next call. To run calls concurrently, use a closure that does not mutate shared captures, or give each call its own state.
- Using a moved value. After
async move, the original variables belong to the closure. Clone before the closure if you still need them. - Mixing up the two forms.
async |x| { ... }and|x| async { ... }are different things. In the second form theasyncblock belongs to the returned value, not to a closure. - Using
?without a return type. See the example above. Annotate with-> Result<_, E>.
Passing an async closure to a function
For now, one example of the receiving side shows how it fits together. A function that accepts an async closure names the bound AsyncFn, AsyncFnMut or AsyncFnOnce, as the next chapter explains:
async fn apply<F>(f: F, n: u32) -> u32
where
F: AsyncFn(u32) -> u32,
{
f(n).await
}
async fn demo() {
let offset = 10;
let result = apply(async |x| x + offset, 5).await;
assert_eq!(result, 15);
}The closure borrows offset from the surrounding scope. The signature has no separate future type parameter, because the bound describes the future's output directly.
An async closure may also satisfy a bound written as Fn(X) -> Fut, but only when its future does not borrow from the closure's own state. Don't rely on that. Use the AsyncFn family when you accept async closures.
Exercise
This code fails to compile with an error about borrowing count as mutable. What single change fixes it? let count = 0; let bump = async || { count += 1; }; bump().await;
Show answer
Declare both bindings as mutable: let mut count = 0; and let mut bump = async || { count += 1; };. The body mutates a capture, so the closure needs &mut access to be called, and the captured variable must itself be mutable.
Exercise
You write let f = async |s: &str| { let n: u32 = s.parse()?; Ok(n) }; and get a type annotation error. Why, and how do you fix it?
Show answer
The compiler cannot infer the error type of the Result because ? can convert from several error types. Add an explicit return type, for example async |s: &str| -> Result<u32, std::num::ParseIntError> { ... }.