Sub topic 3
The classic pattern: closures that return async blocks
This chapter assumes you can read basic Rust ownership and borrowing errors. It also assumes you know Fn, FnMut and FnOnce, and that you have used async fn and .await. The examples use Tokio (tokio = { version = "1", features = ["full"] }) for the runtime.
Before async closures existed in Rust 1.85, a callback that does asynchronous work was an ordinary closure that returns an async block. Most async code written before 2025 uses this pattern. You need to read it fluently, and you need to know where it stops working.
The shape of the pattern
Take a function that calls an async callback twice. The first call's result feeds the second call.
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
}
#[tokio::main]
async fn main() {
let result = apply_twice(|x| async move { x + 1 }, 5).await;
assert_eq!(result, 7);
println!("{result}");
}The caller passes |x| async move { x + 1 }. This closure is not itself async. It is a normal closure whose body is a single expression, an async move block. Calling the closure evaluates that expression and returns a future.
The bound has two type parameters because Rust needs two facts:
F: Fn(u32) -> FutsaysFis callable with au32and returns some typeFut.Fut: Future<Output = u32>says that returned type is a future producing au32.
Every async block has its own anonymous type, so you cannot write it by name. You also cannot write Fn(u32) -> impl Future<Output = u32> in a bound on stable Rust. So you introduce Fut as a generic parameter and let the compiler infer it from the closure.
Two stages: the closure body and the future body
A closure that returns an async block runs code at two different moments. The code before the async keyword runs when you call the closure. The code inside the block runs when something polls the future, usually through .await.
#[tokio::main]
async fn main() {
let f = |x: u32| {
println!("closure body runs for {x}");
async move {
println!("future body runs for {x}");
x + 1
}
};
let fut = f(1);
println!("got the future");
let value = fut.await;
println!("result: {value}");
}The output is:
closure body runs for 1
got the future
future body runs for 1
result: 2This split is useful. You can validate arguments, clone shared handles, or increment a counter eagerly. Then you hand back a future that owns exactly what it needs.
Why `async move` is usually required
Consider |x| async { x + 1 } without move. The async block would borrow x, but x is a parameter owned by the closure call. It is dropped when the closure returns, while the future is still alive. The compiler rejects this with an error about the block borrowing a value it does not own long enough.
Adding move makes the block take ownership of everything it mentions. For a Copy type such as u32 this just copies the value, which is why the pattern looks so uniform.
Captured variables: Copy versus non-Copy
The same move that fixes parameters causes trouble with captured variables. A Copy capture is fine:
use std::future::Future;
async fn apply<F, Fut>(f: F, n: u32) -> u32
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32>,
{
f(n).await
}
#[tokio::main]
async fn main() {
let offset = 10;
let result = apply(|x| async move { x + offset }, 5).await;
assert_eq!(result, 15);
}A non-Copy capture such as a String is different. If you write |x| async move { format!("{prefix}{x}") }, the async move block moves prefix out of the closure. Moving a captured value out is only possible once, so the closure can only be FnOnce. A function that asks for Fn rejects it with an error that says the closure is FnOnce because it moves a variable out of its environment.
The fix is to clone inside the closure body, before the async block. Each call then gives the future its own copy:
use std::future::Future;
async fn label_all<F, Fut>(f: F, ids: &[u32]) -> 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
}
#[tokio::main]
async fn main() {
let prefix = String::from("id-");
let labels = label_all(
|x| {
let prefix = prefix.clone();
async move { format!("{prefix}{x}") }
},
&[1, 2, 3],
)
.await;
println!("{labels:?}");
}The closure only borrows prefix to call clone, so it stays Fn. The async block moves the clone, so the future owns its data and does not point back into the closure. For expensive data, put it in an Arc and clone the Arc instead.
Mutable state with FnMut
If the callee calls the closure several times and the closure changes captured state, use FnMut. Make the mutation in the closure body, not inside the async block:
use std::future::Future;
async fn retry<F, Fut, T, E>(mut attempt: F, times: u32) -> Result<T, E>
where
F: FnMut(u32) -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let mut n = 1;
loop {
match attempt(n).await {
Ok(v) => return Ok(v),
Err(e) if n >= times => return Err(e),
Err(_) => n += 1,
}
}
}
#[tokio::main]
async fn main() {
let mut calls = 0;
let result = retry(
|n| {
calls += 1;
async move {
if n < 3 {
Err(format!("attempt {n} failed"))
} else {
Ok(n * 10)
}
}
},
5,
)
.await;
println!("{result:?} after {calls} calls");
}This prints Ok(30) after 3 calls. The calls += 1 happens at call time, inside the closure body, where the closure has its mutable borrow of calls. Each returned future owns only the copied n. If the async block tried to touch calls itself, the future would hold a borrow into the closure's captured state. That is the failure the next chapter examines.
Plain async functions fit the same bound
An async fn item is a function returning an anonymous future, so it satisfies Fn(u32) -> Fut directly:
use std::future::Future;
async fn apply<F, Fut>(f: F, n: u32) -> u32
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32>,
{
f(n).await
}
async fn add_one(x: u32) -> u32 {
x + 1
}
#[tokio::main]
async fn main() {
assert_eq!(apply(add_one, 1).await, 2);
}Extra bounds you will see
Real code often adds bounds on F and Fut. Multithreaded executors move futures between threads, and tokio::spawn requires a 'static future.
| Bound | Why it is added |
|---|---|
| `Fut: Send` | The future may be polled on another thread, for example inside `tokio::spawn`. |
| `Fut: 'static` | A spawned task cannot borrow from the spawning function. |
| `F: Send` | The closure itself moves to another task or thread. |
| `F: Fn` instead of `FnMut` | The callee may need to call the closure concurrently or through a shared reference. |
| `F: FnOnce` | The callee runs the callback once, which allows the closure to move captures out. |
For example, a helper that starts one task per item needs both Send and 'static on Fut:
use std::future::Future;
use tokio::task::JoinHandle;
fn spawn_each<F, Fut>(f: F, items: Vec<u32>) -> Vec<JoinHandle<u32>>
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32> + Send + 'static,
{
items.into_iter().map(|i| tokio::spawn(f(i))).collect()
}Call it from inside a Tokio runtime. Because f(i) returns a future that owns its data (async move with cloned captures), it satisfies 'static.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| An async block may outlive borrowed value `x` | The block borrows a closure parameter | Use `async move` |
| Expected a closure that implements `Fn`, but this only implements `FnOnce` | `async move` moved a non-`Copy` capture out of the closure | Clone or `Arc::clone` before the block |
| `unused_must_use` warning on a future | You called the closure but never awaited the result | Add `.await` or pass the future on |
| The future does not run | Futures are lazy, so nothing polled it | Await it, or spawn it |
| A callback taking `&str` fails to satisfy the bound | `Fut` is one fixed type, but a borrowed argument gives each call a different lifetime | Covered in the next chapter |
The last row marks where this pattern stops. When the future must borrow from an argument or from the closure's captured state, a single generic Fut cannot express it.
Exercise
This code does not compile when passed to fn run<F, Fut>(f: F) where F: Fn() -> Fut, Fut: Future<Output = usize>. Why, and how do you fix it?
let name = String::from("ferris");
run(|| async move { name.len() });
Show answer
The async move block moves name out of the closure's captured state, which makes the closure FnOnce, but run requires Fn. Fix it by cloning inside the closure body before the block: run(|| { let name = name.clone(); async move { name.len() } });. Alternatively, compute the length eagerly in the closure body (let len = name.len(); async move { len }), so the future captures only a usize.
Exercise
In the code below, in what order do the two messages print, and when does "closure" print relative to the .await?
let f = |x: u32| {
println!("closure");
async move { println!("future"); x }
};
let fut = f(1);
fut.await;
Show answer
"closure" prints first, at the moment f(1) is called, before .await is reached. "future" prints second, when fut.await polls the async block. The closure body runs eagerly, and the async block body runs lazily.