Sub topic 7
How async closures borrow from their captures and arguments
This chapter assumes you know the Fn, FnMut and FnOnce traits, the basics of lifetimes, and the AsyncFn bounds from the previous chapter. It explains what an async closure's future is allowed to borrow, and why the older |x| async move { ... } pattern can't express it.
The future can borrow from the closure
A closure that returns an async block has a fixed return type. When you write F: Fn(u32) -> Fut, Fut is one type, chosen before any call happens. It can't mention the lifetime of the borrow created by a particular call.
An async closure doesn't have this limit. Each call to an AsyncFn closure produces a future that may borrow from the closure's own captured variables, and from the arguments of that call. The AsyncFn traits tie the future's lifetime to each call, not to the type.
async fn call_it<F>(f: F) -> usize
where
F: AsyncFn() -> usize,
{
f().await
}
async fn demo() {
let data = vec![1, 2, 3];
let n = call_it(async || data.len()).await;
assert_eq!(n, 3);
println!("{data:?}");
}The closure captures data by shared reference, and the future reads it through the closure. No clone is needed, and data is still usable afterwards.
Mutable captures and the one-future-at-a-time rule
With AsyncFnMut, the future borrows the closure mutably. So the future from one call must be finished or dropped before the next call starts. The borrow checker enforces this.
async fn run_twice<F>(mut f: F)
where
F: AsyncFnMut(),
{
f().await;
f().await;
}
async fn demo() {
let mut log = Vec::new();
run_twice(async || {
log.push("tick");
})
.await;
assert_eq!(log.len(), 2);
}Here log is captured by mutable reference. Each f().await completes before the next call, so the two mutable borrows never overlap. Calling f() twice and awaiting both futures later would be a compile error.
Borrowed arguments
The same per-call lifetime applies to arguments. In F: AsyncFn(&str), the &str has a fresh lifetime on every call, and the returned future may hold it across .await points.
async fn for_each_word<F>(text: &str, f: F)
where
F: AsyncFn(&str),
{
for word in text.split_whitespace() {
f(word).await;
}
}
async fn demo() {
let prefix = String::from("word:");
for_each_word("a b c", async |w| {
println!("{prefix} {w}");
})
.await;
}The closure borrows prefix from its captures and w from its argument. The generic Fn(&str) -> Fut form can't say this, because Fut can't depend on the argument's lifetime.
`move` and `AsyncFnOnce`
async move || ... moves the captured variables into the closure. It does not move them into each future. An AsyncFn or AsyncFnMut closure still lends its captures to every future it creates. Which trait the closure implements depends on what the body does with its captures. If the body moves a capture out, the closure implements only AsyncFnOnce.
async fn consume<F>(f: F) -> String
where
F: AsyncFnOnce() -> String,
{
f().await
}
async fn demo() {
let name = String::from("ada");
let out = consume(async move || name).await;
assert_eq!(out, "ada");
}Limits to know
- The
Outputtype is fixed by the bound. A future can borrow from an argument while it runs, but the value it returns can't borrow from that argument. - A bound like
F: AsyncFn() + Sendonly makes the closureSend. In generic code, stable Rust has no way to also require that the returned future isSend. This can matter with multithreaded executors, and the later chapters on trait methods return to the issue.
Exercise
A function takes mut f: F where F: AsyncFnMut(). Why does let a = f(); let b = f(); a.await; b.await; fail to compile?
Show answer
Each future from an AsyncFnMut call holds a mutable borrow of the closure until it is finished or dropped. Creating b while a is still alive requires a second mutable borrow, which the borrow checker rejects. Awaiting each call before making the next one fixes it.