Sub topic 4
Where the classic pattern breaks: borrowed arguments and captured state
This chapter assumes you know how closures capture variables, how Fn, FnMut, and FnOnce differ, and how async fn and .await work. The previous chapter showed the pattern |x| async move { ... }, which is a normal closure that returns a future. It works well when the future owns everything it needs. It fails when the future must borrow.
The problem in one sentence
A closure that returns a future has two types: the closure type and the future type Fut. The bound F: Fn(A) -> Fut fixes Fut as one concrete type for all calls. A future that borrows from its argument has a type that depends on how long that borrow lasts, and that lifetime can differ on every call. One fixed Fut cannot express this.
Failure 1: borrowed arguments
This helper passes each line to an async callback as a &str:
use std::future::Future;
async fn for_each_line<F, Fut>(lines: &[String], f: F)
where
F: Fn(&str) -> Fut,
Fut: Future<Output = ()>,
{
for line in lines {
f(line).await;
}
}
async fn demo() {
let lines = vec![String::from("a"), String::from("b")];
// Does not compile: the future borrows `line`.
for_each_line(&lines, |line| async move { println!("{line}"); }).await;
}Fn(&str) -> Fut means "for every lifetime 'a, take &'a str". Fut is chosen once, outside that "for every". The async block holds line, so its type mentions 'a. The compiler reports that the returned future requires one lifetime to outlive another, and it cannot be satisfied.
The usual workaround is to give the future an owned value:
use std::future::Future;
async fn for_each_line<F, Fut>(lines: &[String], f: F)
where
F: Fn(String) -> Fut,
Fut: Future<Output = ()>,
{
for line in lines {
f(line.clone()).await;
}
}
async fn demo() {
let lines = vec![String::from("a"), String::from("b")];
for_each_line(&lines, |line| async move { println!("{line}"); }).await;
}This compiles, but each call allocates a new String. The API also forces every caller to accept owned data.
Failure 2: captured state
The same limit appears with FnMut. Suppose the closure mutates a captured counter and returns a future:
// Does not compile.
let mut count = 0;
run_twice(|| async { count += 1; }).await;The future borrows count through the closure. But calling an FnMut closure only borrows the closure for the duration of the call. The future would outlive that borrow, so the compiler reports "captured variable cannot escape FnMut closure body".
Switching to async move does not help. For a Copy type like i32, the future gets its own copy, so the original count never changes. The standard fix is shared ownership:
use std::future::Future;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
async fn run_twice<F, Fut>(mut f: F)
where
F: FnMut() -> Fut,
Fut: Future<Output = ()>,
{
f().await;
f().await;
}
async fn demo() {
let count = Arc::new(AtomicU32::new(0));
run_twice(|| {
let count = Arc::clone(&count);
async move {
count.fetch_add(1, Ordering::SeqCst);
}
})
.await;
assert_eq!(count.load(Ordering::SeqCst), 2);
}A plain counter has become an Arc and an atomic, plus a clone on every call.
What you need instead
To fix this properly, the language has to treat the closure and the future it returns as one unit. The returned future must be allowed to borrow from the arguments and from the closure's captures. The next chapters introduce async closures, which do this.
Exercise
Why does F: Fn(&str) -> Fut fail when the closure returns async move { println!("{line}") }, but F: Fn(String) -> Fut succeeds?
Show answer
Fut is one fixed type, but the borrowed &str has a lifetime that differs per call, and the async block's type includes that lifetime. A String is owned and has no lifetime, so one Fut type works for every call.
Exercise
A closure || async move { total += 1 } captures total: u32 and is passed to a function that takes F: FnMut() -> Fut. After two calls, why is the outer total still 0?
Show answer
async move copies a Copy value like u32 into each future, so each future increments its own copy and the original is never modified.