Sub topic 5
Writing async closures
This chapter assumes you know ordinary closures and the Fn traits, async fn and .await, and the idea that a future does nothing until it is polled. The chapter before this one showed the older pattern, |x| async move { ... }. Here you will write the same logic as an async closure, available since Rust 1.85.
The syntax
An async closure puts async in front of the parameter list:
let add_one = async |x: u32| x + 1;
let say_hi = async || println!("hi");
let owned = async move |x: u32| x + offset;Each form mirrors a normal closure. async comes before move, and the body can be a single expression or a block. The closure's return type is the type of the body, not the future. Writing async |x| -> u32 { x } is allowed when you need to name it.
Compare the two styles side by side:
| Style | Written as | Return type of the closure | Column | Column |
|---|---|---|---|---|
| Closure returning an async block | `\ | x\ | async move { x + 1 }` | An unnamed future type |
| Async closure | `async \ | x\ | x + 1` | A future produced by the closure itself |
Both produce a future when called. The difference is how the compiler relates that future to the closure's borrows, which the next chapters cover.
A runnable example
The program below needs no external crate. It defines a minimal block_on using Waker::noop (stable in 1.85) so you can run it with plain cargo run. The futures here finish on the first poll, so a busy loop is enough.
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 apply<F>(f: F, n: u32) -> u32
where
F: AsyncFn(u32) -> u32,
{
f(n).await
}
fn main() {
let offset = 10;
let add = async |x: u32| x + offset;
assert_eq!(block_on(apply(add, 5)), 15);
let name = String::from("Ferris");
let greet = async move |greeting: &str| format!("{greeting}, {name}!");
let message = block_on(async { greet("Hello").await });
assert_eq!(message, "Hello, Ferris!");
println!("{message}");
}Three things to notice:
addcapturesoffsetby reference, exactly as a normal closure would. Withoutmove, the closure borrows.greetusesmove, so it ownsname. Calling it does not consume it, so you can call it again.greeting: &stris a borrowed argument. The classic pattern struggles with this case when the future holds the borrow. Async closures are designed to handle it.
The AsyncFn(u32) -> u32 bound on apply is the async counterpart of Fn(u32) -> u32. The next chapter covers it and its siblings in detail.
Common errors
- Forgetting
.await.let v = f(5);gives you a future, not au32. The compiler usually warns about an unused future, but it will not warn when you pass the future somewhere that accepts any type. - Writing
asyncafter the pipes.|x| async { ... }is the old pattern and creates a closure returning an async block. The keyword must come first:async |x| .... - Using it on an older toolchain. Before Rust 1.85 the compiler rejects
async |x|with an error saying async closures are unstable. Runrustc --versionand update if needed. - Expecting
moveto be automatic. If the closure must outlive the scope that owns its captures, such as when you spawn it, addmoveas you would for a normal closure.
Exercise
Rewrite |s: String| async move { s.len() } as an async closure. Then say what it returns when called, and what it takes to get the usize.
Show answer
async |s: String| s.len(). Calling it returns a future, and the body has not run yet. Awaiting that future, for example f(String::from("abc")).await, runs the body and yields the usize (3 here).