Sub topic 4
Where the classic pattern breaks: borrowed arguments and captured state
This chapter assumes you know three things. You can read basic Rust lifetimes. You know the Fn, FnMut, and FnOnce traits. You have written a closure of the form |x| async move { ... }. The previous chapter showed that this pattern works well when everything is owned. Here you will see the two situations where it fails, and why the compiler rejects them.
The shape of the pattern
The classic bound uses two type parameters. F is the closure. Fut is the future it returns.
use std::future::Future;
async fn call_with<F, Fut>(f: F, n: u32) -> u32
where
F: Fn(u32) -> Fut,
Fut: Future<Output = u32>,
{
f(n).await
}
async fn demo() {
let result = call_with(|x| async move { x * 2 }, 21).await;
assert_eq!(result, 42);
}Fut is chosen once, when the caller instantiates call_with. It is one concrete type. Every call to f must return exactly that type. Both failures below come from this fact.
Failure 1: a borrowed argument
Suppose the callee passes a reference to the closure. The reference is valid only for one loop iteration.
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.
for_each_line(&lines, |line| async move {
println!("{line}");
})
.await;
}The function for_each_line itself compiles. The error appears at the call site:
error: lifetime may not live long enough
| for_each_line(&lines, |line| async move {
| ----- ^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
| |
| return type of closure `{async block}` contains a lifetime `'2`
| has type `&'1 str`Why it fails
Fn(&str) -> Fut is shorthand for for<'a> Fn(&'a str) -> Fut. The closure must accept a reference of any lifetime 'a. But Fut is declared outside the for<'a>, so it cannot mention 'a.
The async block in the closure stores line, which has type &'a str. Its type is therefore something like {async block}<'a>, a different type for each 'a. The bound needs one type that works for all of them. No such type exists.
In short, the return type of an Fn closure can't depend on the lifetime of its arguments. A future that holds a borrowed argument needs exactly that dependency.
Workarounds with the classic pattern
You have three options. Each has a cost.
- Pass owned data. Change the bound to
Fn(String) -> Futand clone each line. The future then borrows nothing from the argument. The cost is an allocation per call. - Box the future and name the lifetime. The return type can then mention
'a, becauseBoxFuture<'a, ()>is written inside thefor<'a>binder. - Use a named
async fninstead of a closure. This still needs a higher-ranked bound on the callee, which the classic pattern can't write forFut.
Option 2 looks like this:
use std::future::Future;
use std::pin::Pin;
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
async fn for_each_line<F>(lines: &[String], f: F)
where
F: for<'a> Fn(&'a str) -> BoxFuture<'a, ()>,
{
for line in lines {
f(line).await;
}
}
async fn demo() {
let lines = vec![String::from("a"), String::from("b")];
for_each_line(&lines, |line| {
Box::pin(async move {
println!("{line}");
})
})
.await;
}This compiles, but it costs a heap allocation on every call and an indirect call on every poll. The signature also gets harder to read. Callers must remember Box::pin, and forgetting it gives a confusing type error.
Failure 2: captured state
The second failure involves variables the closure captures from its environment. There are two variants.
Moving a capture into the future
use std::future::Future;
async fn run_n<F, Fut>(f: F)
where
F: Fn(u32) -> Fut,
Fut: Future<Output = ()>,
{
f(1).await;
f(2).await;
}
async fn demo() {
let prefix = String::from("n=");
// Does not compile.
run_n(|n| async move { println!("{prefix}{n}"); }).await;
}The async move block takes ownership of prefix. To satisfy that, the closure must own prefix and give it away when called. A closure that gives away a captured value can only be called once, so it is FnOnce. The compiler reports that it "expected a closure that implements the Fn trait, but this closure only implements FnOnce".
Removing move does not help. The block then borrows n, which is a local variable of the closure call. The future would outlive it, and the compiler rejects that too.
The fix is to clone inside the closure, then move the clone into the block:
use std::future::Future;
async fn run_n<F, Fut>(f: F)
where
F: Fn(u32) -> Fut,
Fut: Future<Output = ()>,
{
f(1).await;
f(2).await;
}
async fn demo() {
let prefix = String::from("n=");
run_n(|n| {
let prefix = prefix.clone();
async move {
println!("{prefix}{n}");
}
})
.await;
}Each call now produces a future that owns its own String. The closure only reads prefix to clone it, so it stays Fn.
Mutating a capture from the future
Now the closure should update shared state:
use std::future::Future;
async fn run_twice<F, Fut>(mut f: F)
where
F: FnMut() -> Fut,
Fut: Future<Output = ()>,
{
f().await;
f().await;
}
async fn demo() {
let mut count = 0;
// Does not compile.
run_twice(|| async {
count += 1;
})
.await;
}The error is captured variable cannot escape FnMut closure body.
FnMut::call_mut takes &mut self. That borrow lasts only for one call. The future needs to keep using count after call_mut returns, which means it would hold a reborrow of the closure's own state. But the return type Fut cannot depend on the lifetime of &mut self, for the same reason it could not depend on an argument lifetime.
The usual fix is shared ownership with interior mutability, so that each future owns a handle:
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);
}This works, but you have changed the data type (u32 to Arc<AtomicU32>) only to satisfy the trait signature. Use Arc<Mutex<T>> for non-atomic state, or Rc<Cell<T>> when the executor is single-threaded.
Where the lifetime link is missing
Both failures share one cause. The bound has a single Fut that is fixed before any call happens. The table lists what that future would need to borrow from.
| What the future needs | Lifetime it would depend on | Why `Fn(..) -> Fut` can't express it |
|---|---|---|
| A reference argument | The `'a` in `for<'a> Fn(&'a T)` | `Fut` is declared outside the `for<'a>` binder |
| State inside an `FnMut` closure | The `&mut self` borrow of one `call_mut` | `Output` is an associated type with no access to the call's `self` lifetime |
| A moved capture | None, but the closure becomes `FnOnce` | `Fn` and `FnMut` can't give away a captured value |
Recognizing the errors
You will meet these messages most often:
lifetime may not live long enough ... returning this value requires that '1 must outlive '2: a future holds a borrowed argument.captured variable cannot escape FnMut closure body: a future holds a borrow of the closure's mutable state.expected a closure that implements the Fn trait, but this closure only implements FnOnce: anasync moveblock moved a capture out of the closure.async block may outlive the current function, but it borrows ...: you droppedmoveand the block borrows a closure-local variable.
All four disappear once the future is allowed to borrow from the call. That is what async closures do. The next chapter introduces the async |x| ... syntax, which gives the closure's future a type that is tied to the call.
Exercise
A function takes F: Fn(&String) -> Fut, Fut: Future<Output = usize>. A caller passes |s| async move { s.len() }. Why does this fail to compile, and what is the smallest change to the closure alone, with the bound left as it is, that makes it compile?
Show answer
The async block holds s: &'a String, so its type depends on 'a. But Fut is fixed outside the for<'a> binder and can't mention 'a. Compute the value before building the future, so the future holds no reference: |s| { let n = s.len(); async move { n } }. The future now owns a usize, and its type no longer depends on 'a.
Exercise
Why does || async { count += 1; } fail with FnMut, but || { let count = Arc::clone(&count); async move { count.fetch_add(1, Ordering::SeqCst); } } succeed?
Show answer
In the first version the future borrows count through the closure's &mut self, which is valid only for the duration of one call_mut. The return type Fut can't depend on that lifetime, so the borrow would escape the closure body. In the second version each future owns its own Arc handle, so it borrows nothing from the closure. The closure itself only reads count to clone it.