Sub topic 3
The classic pattern: closures that return async blocks
This chapter assumes you know ownership and borrowing, the Fn, FnMut and FnOnce traits, and basic async/.await. Before Rust 1.85 there was no async closure syntax. Code that needed an "async callback" used a pattern built from parts you already know.
The idea
An async fn returns a future when called, and the body does not run until the future is awaited. A closure can do the same thing. It is an ordinary closure whose body is an async block. Calling the closure runs no async code. It only builds the future.
use std::future::Future;
async fn apply_twice<F, Fut>(f: F, n: u32) -> u32
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32>,
{
let once = f(n).await;
f(once).await
}
async fn demo() {
let result = apply_twice(|x| async move { x + 1 }, 5).await;
assert_eq!(result, 7);
}Calling f(n) returns a value of type Fut. Awaiting that value produces the u32. The two steps are separate.
Why there are two type parameters
The bound F: Fn(u32) -> Fut needs a name for the closure's return type. Every async block has its own anonymous type, so you cannot write that type out. You introduce a second generic parameter, Fut, and constrain it with Future<Output = u32>. The compiler infers both when you pass the closure.
You can see it as two layers:
Fis the closure type. It implementsFn(u32) -> Fut.Futis what the closure returns. It implementsFuture<Output = u32>.
Why `async move` is usually required
An async block without move borrows the variables it uses. In |x| async { x + 1 } the parameter x is a local of the closure call. The block would hold a reference to x, and the closure would return that block. The reference outlives x, so the compiler rejects it with an error like "async block may outlive the current function, but it borrows x".
Adding move makes the block take ownership of x. The returned future then owns everything it needs. This is why almost every example of the pattern reads |x| async move { ... }.
Owned arguments work well
When the argument is owned, the pattern works with no extra effort. The future takes the value and holds it until it finishes.
use std::future::Future;
async fn apply_to_all<F, Fut>(items: Vec<String>, f: F) -> Vec<usize>
where
F: Fn(String) -> Fut,
Fut: Future<Output = usize>,
{
let mut out = Vec::new();
for item in items {
out.push(f(item).await);
}
out
}
async fn demo() {
let items = vec![String::from("a"), String::from("bcd")];
let lengths = apply_to_all(items, |s| async move { s.len() }).await;
assert_eq!(lengths, vec![1, 3]);
}Each String moves into the closure, and from there into the async block. Nothing is borrowed, so no lifetime problem arises.
Captured state needs a clone
A closure that is Fn may be called many times, so it cannot hand its captured values to a future. Moving a captured String into the block would make the closure FnOnce. The usual fix is to clone the value inside the closure, before the block.
use std::future::Future;
async fn label_all<F, Fut>(ids: &[u32], f: F) -> Vec<String>
where
F: Fn(u32) -> Fut,
Fut: Future<Output = String>,
{
let mut out = Vec::new();
for &id in ids {
out.push(f(id).await);
}
out
}
async fn demo() {
let prefix = String::from("id-");
let labels = label_all(&[1, 2], |n| {
let prefix = prefix.clone();
async move { format!("{prefix}{n}") }
})
.await;
assert_eq!(labels, vec!["id-1", "id-2"]);
}Here the closure body has two statements. The clone runs when the closure is called. The async move block then takes that copy. Each future owns its own prefix, so the closure stays Fn.
Summary of the pattern
- Write the callback as
|args| async move { ... }. - Declare two generic parameters: one for the closure and one for the future it returns.
- Bound the closure with
Fn,FnMutorFnOncereturning the future parameter. Bound the future withFuture<Output = T>. - Give the returned future ownership of whatever it uses, by moving or cloning.
Exercise
In apply_twice(|x| async { x + 1 }, 5), why does the compiler reject the closure, and what is the smallest change that fixes it?
Show answer
The async block borrows x, which is a local of the closure call, and the closure returns the block, so the borrow would outlive x. Adding move, as in |x| async move { x + 1 }, makes the block own x and fixes the error.