Sub topic 7
How Async Closures Borrow from Their Captures and Arguments
This chapter assumes you know closures and the Fn, FnMut and FnOnce traits, basic async/await, and lifetimes. It also assumes you have seen async |x| ... syntax and AsyncFn bounds. The focus here is how the future an async closure returns relates to the closure's own data and to its arguments. You need Rust 1.85 or later.
The core idea: the future borrows from the closure
A closure of the form |x| async move { ... } produces a future that is independent of the closure. The future must own everything it uses, or borrow only from things that outlive the call. The closure's return type is one fixed type, Fut, and it cannot mention the lifetime of a particular call.
An async closure works differently. The future it returns may borrow from the closure itself, which means from its captured variables, and also from the arguments of that call. The closure acts as a lending closure: each call lends part of its state to the future it returns.
This explains three things you will see in practice:
- A body that only reads a capture does not need to clone it.
- A body that mutates a capture is still a valid closure.
- The trait the closure implements depends on how the body uses its captures.
Reading captures: AsyncFn
Capture modes follow the normal closure rules. Without move, each variable is captured by the weakest mode the body needs: shared reference, mutable reference, or move. A body that only reads gives a closure that implements AsyncFn.
async fn call_twice<F>(f: F) -> usize
where
F: AsyncFn() -> usize,
{
f().await + f().await
}
async fn demo() {
let name = String::from("ferris");
let n = call_twice(async || name.len()).await;
assert_eq!(n, 12);
println!("{name}"); // still usable: the closure only borrowed it
}The classic version needs let name = name.clone(); inside the closure before an async move block. Without that, the async block moves name out of the closure, and the closure can then only run once.
The move keyword behaves differently here. In async move |x| ... the closure owns its captures, but the future still borrows them from the closure. Moving into the closure does not move into the future.
Mutating captures: AsyncFnMut
If the body mutates a capture, the closure implements AsyncFnMut. Calling it takes &mut self, so the returned future holds a mutable borrow of the closure's state.
async fn pause() {}
async fn collect<F>(n: u32, mut f: F)
where
F: AsyncFnMut(u32),
{
for i in 0..n {
f(i).await;
}
}
async fn demo() {
let mut seen = Vec::new();
collect(3, async |i| {
pause().await;
seen.push(i);
})
.await;
assert_eq!(seen, [0, 1, 2]);
}Each f(i) returns a future that borrows f mutably. You must finish or drop that future before the next call. This compiles because the loop awaits each future before starting the next. Code such as let a = f(1); let b = f(2); a.await; b.await; is rejected, because two live futures would each hold &mut f.
The closure's mutable borrow of seen ends when collect returns and drops the closure. That is why seen is readable afterward.
The classic pattern cannot do this directly. In |i| async { seen.push(i); }, the future would hold a reference into the closure's captured state. A plain FnMut returns a future type that cannot depend on the borrow of &mut self. The compiler reports that a captured variable cannot escape the FnMut closure body. The usual workaround is shared ownership such as Arc<Mutex<_>>, which changes your data model to suit the closure.
Moving out of captures: AsyncFnOnce
If the body consumes a capture, the closure can run only once. It implements AsyncFnOnce and nothing stronger.
async fn consume<F>(f: F) -> String
where
F: AsyncFnOnce() -> String,
{
f().await
}
async fn demo() {
let owned = String::from("moved");
let s = consume(async move || owned).await;
assert_eq!(s, "moved");
}Passing this closure where AsyncFn or AsyncFnMut is required is a compile error. The compiler chooses the strongest trait the body allows. The next diagram shows the decision.
Each trait is a subtrait of the next weaker one. A function that asks for AsyncFnOnce accepts every async closure. A function that asks for AsyncFn accepts the fewest.
Borrowing from arguments
The second half of the chapter is about arguments. Take the bound F: AsyncFn(&str) -> usize. The elided lifetime is higher-ranked, meaning the closure must work for any lifetime 'a. The future returned by a call with &'a str is allowed to hold that &'a str.
async fn pause() {}
async fn longest<F>(words: &[String], f: F) -> usize
where
F: AsyncFn(&str) -> usize,
{
let mut best = 0;
for w in words {
best = best.max(f(w.as_str()).await);
}
best
}
async fn demo() {
let words = vec![String::from("a"), String::from("abc")];
let bonus = 10;
let n = longest(&words, async |w| {
pause().await;
w.len() + bonus
})
.await;
assert_eq!(n, 13);
}Here w is borrowed across an .await, and bonus is borrowed from the surrounding function. Both borrows sit in one future without any cloning.
The classic bound F: Fn(&str) -> Fut, Fut: Future<Output = usize> fails for the same body. Fut is a single type parameter chosen once, so it cannot be a different type for each lifetime of &str. The usual error is "lifetime may not live long enough" or a type mismatch involving the argument's lifetime.
Classic pattern versus async closure
| Situation | `\ | x\ | async move { ... }` | `async \ | x\ | ...` |
|---|---|---|---|---|---|---|
| Read a captured `String` | Clone first, or the closure becomes `FnOnce` | Borrowed directly | ||||
| Mutate a captured counter | Needs `Arc<Mutex<_>>` or atomics | Plain `&mut` capture, `AsyncFnMut` | ||||
| Borrowed argument `&str` held across `.await` | Fails with a generic `Fut` | Works with `AsyncFn(&str)` | ||||
| Name the future type | `Fut` generic parameter | Not nameable on stable |
The last row is the main cost. The future type of an async closure has no stable name, and you cannot write a bound like "this future is Send". If the callee must spawn the future on a multithreaded executor, the classic form with Fut: Future + Send + 'static may still be the right choice.
Putting it together
This program runs the three cases with no external crates. The block_on helper polls a future in a loop. It works here because none of the futures wait on real I/O. Waker::noop is stable since 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(v) = fut.as_mut().poll(&mut cx) {
return v;
}
}
}
async fn pause() {}
async fn longest<F>(words: &[String], f: F) -> usize
where
F: AsyncFn(&str) -> usize,
{
let mut best = 0;
for w in words {
best = best.max(f(w.as_str()).await);
}
best
}
async fn collect<F>(n: u32, mut f: F)
where
F: AsyncFnMut(u32),
{
for i in 0..n {
f(i).await;
}
}
async fn consume<F>(f: F) -> String
where
F: AsyncFnOnce() -> String,
{
f().await
}
async fn demo() {
let words = vec![String::from("a"), String::from("abc")];
let bonus = 10;
let n = longest(&words, async |w| {
pause().await;
w.len() + bonus
})
.await;
assert_eq!(n, 13);
let mut seen = Vec::new();
collect(3, async |i| {
pause().await;
seen.push(i);
})
.await;
assert_eq!(seen, [0, 1, 2]);
let owned = String::from("moved");
let s = consume(async move || owned).await;
assert_eq!(s, "moved");
println!("ok");
}
fn main() {
block_on(demo());
}Common errors
- "Closure implements
AsyncFnOnce, notAsyncFn." The body moves a capture out, for example by returning it or passing it to a function that takes ownership. Borrow it, clone it, or change the bound toAsyncFnOnce. - Two calls alive at once on an
AsyncFnMut. Await the first future before calling again. Do not collect futures from anAsyncFnMutinto aVecor pass them tojoin!. - Using
|x| async { ... }with a borrowedx. Switch toasync |x| ...and anAsyncFn(&T)bound. This also fixes the case where the block needsmoveonly to avoid a borrow error. - Expecting
dyn AsyncFn. These traits are not dyn compatible. Use a generic parameter, or box the future by hand and acceptFn(&str) -> Pin<Box<dyn Future<Output = usize> + '_>>, which costs an allocation per call.
Exercise
A function takes f: F where F: AsyncFn(). You pass async || { counter += 1; } where counter is a local u32. Why does this fail, and which one change to the bound fixes it?
Show answer
The body mutates a captured variable, so the closure only implements AsyncFnMut (and AsyncFnOnce). It cannot implement AsyncFn, whose call takes &self. Change the bound to F: AsyncFnMut() and declare the parameter as mut f: F so the function can call it with &mut.
Exercise
Why does F: Fn(&str) -> Fut, Fut: Future<Output = usize> reject a closure whose future holds the &str across an .await, while F: AsyncFn(&str) -> usize accepts the equivalent async closure?
Show answer
Fut is one type chosen for the whole bound, so it cannot depend on the lifetime of each call's &str. With AsyncFn(&str), the lifetime is higher-ranked and the future returned by each call is allowed to borrow from that call's argument.
Exercise
An async closure body returns a captured String by value. Which of AsyncFn, AsyncFnMut and AsyncFnOnce does it implement?
Show answer
Only AsyncFnOnce. Returning the String moves it out of the closure's captured state, so the closure can be called once.