skip to content

In Rust, why does a retry helper bounded by `F: FnMut() -> Fut` reject `|| async { log.push(..) }`, and how does an `AsyncFnMut` bound fix it?

level: seniorimportance: should knowfreq 32%

answer

  1. one Fut type for every call
  2. the future borrows the closure
  3. captured variable cannot escape
  4. a lending call: &mut self
  5. stable since 1.85

basics

~20 s

With FnMut() -> Fut, one future type is fixed for every call, so a returned future cannot borrow the closure's captured log. AsyncFnMut, stable since Rust 1.85, lets each call's future borrow the closure's state, so an async closure can push to log.

solid answer

~40 s

The bound `F: FnMut() -> Fut, Fut: Future` names a single `Fut` type chosen before any call, so the returned future cannot hold a borrow of the closure that produced it. `|| async { log.push(..) }` returns an `async` block borrowing the captured `log` mutably, so rustc refuses it: "captured variable cannot escape `FnMut` closure body". Rust 1.85 stabilised async closures (`async || { .. }`) and the `AsyncFn`, `AsyncFnMut` and `AsyncFnOnce` traits, which are in the prelude of every edition. `AsyncFnMut::async_call_mut` takes `&mut self` and returns a future that may borrow from the closure, so with `F: AsyncFnMut() -> Result<u32, String>` the helper can call `op().await` in a loop and each attempt can mutate `log`. The traits' associated types are still unstable, so bounds use the `AsyncFnMut() -> T` sugar.

code

rust · 22 lines
rust
async fn retry<F>(attempts: u32, mut op: F) -> Result<u32, String>
where
    F: AsyncFnMut() -> Result<u32, String>,
{
    let mut last = Err(String::from("never ran"));
    for _ in 0..attempts {
        last = op().await;
        if last.is_ok() {
            break;
        }
    }
    last
}

fn main() {
    let mut log: Vec<String> = Vec::new();
    let result = futures::executor::block_on(retry(3, async || {
        log.push(format!("attempt {}", log.len() + 1));
        Err::<u32, String>(String::from("busy"))
    }));
    println!("{result:?} after {} attempts", log.len());
}

go deeper

for a junior

Recall that async closures are written async || { .. }, and that AsyncFn, AsyncFnMut and AsyncFnOnce are their trait bounds since Rust 1.85.

for a middle

Explain why one Fut type cannot borrow from the closure that produced it, and how the AsyncFn traits mirror Fn, FnMut and FnOnce.

for a senior

Diagnose the captured-variable-cannot-escape error in a callback helper, migrate its bound to AsyncFnMut, and know which callers keep compiling.

for a principal

Decide when a library can require Rust 1.85 for AsyncFn bounds versus keeping the two-type pattern, given its supported compilers and Send needs.

## The two-type pattern and its limit Before Rust 1.85, a function that accepted "something async to call" wrote two generic parameters: ```rust async fn retry<F, Fut>(attempts: u32, mut op: F) -> Result<u32, String> where F: FnMut() -> Fut, Fut: Future<Output = Result<u32, String>>, ``` `Fut` is **one type**, fixed when `retry` is instantiated. The future returned by each call to `op` must therefore be independent of that particular call, and in particular it **cannot borrow from the closure itself**, because `FnMut::call_mut`'s `&mut self` borrow ends when the call returns, while the future lives on. That rules out the most natural code: ```rust let mut log = Vec::new(); retry(3, || async { log.push(String::from("try")); Err(String::from("busy")) }) ``` The closure captures `log` by `&mut`, and the `async` block it returns borrows that capture. rustc 1.99.1 refuses it with an error that carries no E-code: ```plaintext error: captured variable cannot escape `FnMut` closure body = note: `FnMut` closures only have access to their captured variables while they are executing... = note: ...therefore, they cannot allow references to captured variables to escape ``` The usual workarounds were to clone or `Arc::clone` the state into each future (`move || { let log = log.clone(); async move { .. } }`), wrap it in a `Mutex`, or pass it as an argument on every call. ## Async closures and the AsyncFn traits **Rust 1.85** stabilised **async closures**, written `async || { .. }` or `async move || { .. }`, and three traits in `core::ops`, re-exported in the prelude of all editions: | Trait | Call receiver | The returned future may | |---|---|---| | `AsyncFnOnce` | `self` | move out of the closure's captures | | `AsyncFnMut` | `&mut self` | borrow the captures mutably | | `AsyncFn` | `&self` | borrow the captures shared | `AsyncFnMut` is a supertrait of `AsyncFn`, and `AsyncFnOnce` of `AsyncFnMut`, mirroring `Fn: FnMut: FnOnce`. The docs for `AsyncFn::async_call` and `AsyncFnMut::async_call_mut` say each returns "a future which may borrow from the called closure"; `AsyncFnOnce::async_call_once` returns one that may move out of it. That borrowing, a **lending** call, is precisely what the `FnMut() -> Fut` bound cannot express. ## Rewriting the helper ```rust async fn retry<F>(attempts: u32, mut op: F) -> Result<u32, String> where F: AsyncFnMut() -> Result<u32, String>, ``` Inside, `op().await` borrows `op` mutably for the duration of each attempt; the borrow ends when that attempt's future completes, so the next iteration can call it again. The caller passes `async || { log.push(..); Err(..) }` and it compiles. The bound names only the output type; there is no `Fut` parameter at all. ## Edge facts worth knowing - **Plain closures and `async fn` items still fit.** The std docs say all `async fn`s and functions returning futures implement these traits, so `retry(3, fetch_once)` and `retry(3, || async { .. })` (one that borrows nothing) both satisfy an `AsyncFnMut` bound. Switching a bound from `FnMut() -> Fut` to `AsyncFnMut` does not break callers that passed such values. - **A capturing async closure does not fit the old bound.** Passing `async move || Ok(n)` (with `n: u32`) to `F: FnMut() -> Fut` fails on rustc 1.99.1 with "async closure does not implement `FnMut` because it captures state from its environment"; a non-capturing `async || 5` does fit. - **The associated types are unstable.** Writing `F::Output` or `F::CallRefFuture<'_>` is E0658, "use of unstable library feature `async_fn_traits`", so stable code spells bounds as `AsyncFn(Args) -> T`. - **Async closures work on older editions.** They need edition 2018 or later for `async`, not edition 2024. - **`Send` is not expressible yet** on the returned future through the sugar alone, which matters when the helper spawns; that problem belongs with spawning and Send futures. ## Choosing in code review 1. New async helper that calls a callback repeatedly: bound it with `AsyncFnMut` (or `AsyncFn` when it calls concurrently through `&self`). 2. Callers that mutate captured state: write `async || { .. }`, not `|| async { .. }`. 3. Code that must also build on compilers older than 1.85: keep `FnMut() -> Fut` and clone state into each future.

  • Can you still pass an `async fn` item or a non-borrowing `|| async { .. }` closure to a helper bounded by `AsyncFnMut`?
    Yes. The std docs state that all `async fn`s and functions returning futures implement the `AsyncFn` traits, so an `async fn` item and an ordinary closure returning a future both satisfy the bound. Migrating a helper from `FnMut() -> Fut` to `AsyncFnMut` therefore keeps those callers compiling.
  • Why does `async move || Ok(n)` with `n: u32` fail an `F: FnMut() -> Fut` bound even though it only copies a number?
    The async closure's future borrows the closure's own captured state, so it cannot be described by a single `Fut` type; rustc 1.99.1 says "async closure does not implement `FnMut` because it captures state from its environment". Either bound the helper with `AsyncFnMut`, or write `move || async move { Ok(n) }`, whose future owns its own copy.
  • Can a stable bound name the future type that an `AsyncFn` returns?
    No. `AsyncFnOnce::Output`, `CallOnceFuture` and `CallRefFuture` are unstable under `async_fn_traits`, so naming them is E0658 on stable. Stable code writes `F: AsyncFn(Args) -> T`; when a caller needs the future to be `Send`, that cannot be stated through this sugar today.

  • || async { .. } and async || { .. } are just two spellings of the same thing.
  • The FnMut() -> Fut bound fails only because log is not Send.
  • AsyncFn traits need the 2024 edition because they are not in older preludes.
  • Stable code can write F::Output to name an AsyncFn's result type.
  • An AsyncFnMut bound rejects ordinary async fn items passed as callbacks.

Assumes Rust 1.85 or later (checked on 1.99): async closures and the AsyncFn, AsyncFnMut and AsyncFnOnce traits were stabilised in 1.85 and added to every edition's prelude.