Sub topic 6
Accepting async closures with AsyncFn, AsyncFnMut, and AsyncFnOnce
This chapter assumes you know the Fn, FnMut, and FnOnce traits, can write basic async/await code, and have read the previous chapter on writing async |x| ... closures. Here you will learn how to write the receiving side: a function that accepts an async closure and calls it.
The three traits
Rust 1.85 added three traits to the standard library prelude. They mirror the closure traits you already know.
| Trait | Callee can call it | Closure body may |
|---|---|---|
| `AsyncFnOnce` | once, consuming the closure | move captured values out |
| `AsyncFnMut` | many times, one future at a time | mutate captured values |
| `AsyncFn` | many times, several futures at once | only read captured values |
The traits form the same chain as Fn, FnMut, and FnOnce. Every AsyncFn closure is also AsyncFnMut, and every AsyncFnMut closure is also AsyncFnOnce. The compiler picks the most capable trait your closure body allows, so you rarely have to choose on the caller's side. The function that accepts the closure makes the choice.
The parenthesized sugar looks like the Fn family. F: AsyncFn(u32) -> u32 means that calling F with a u32 gives a future whose Output is u32. The -> u32 describes what the future produces after .await, not what the call returns directly. There is no separate Fut type parameter to declare.
AsyncFn: shared access
Use AsyncFn when the closure only reads its captures.
async fn apply<F>(f: F, n: u32) -> u32
where
F: AsyncFn(u32) -> u32,
{
f(n).await
}
async fn demo() {
let offset = 10;
let result = apply(async |x| x + offset, 5).await;
assert_eq!(result, 15);
}The closure borrows offset and apply receives it by value. Compare this with the classic pattern from earlier chapters, where you needed F: Fn(u32) -> Fut, Fut: Future<Output = u32>. The new bound has one parameter fewer.
An AsyncFn call needs only &self. That means two futures from the same closure can be alive at once.
async fn both<F>(f: F) -> u32
where
F: AsyncFn(u32) -> u32,
{
let a = f(1);
let b = f(2);
a.await + b.await
}Both futures hold a shared borrow of f. Nothing in this function runs the futures concurrently, but the code shows what the bound allows. If you pass the same closure to a join combinator, the two futures can make progress together.
AsyncFnMut: exclusive access
Use AsyncFnMut when the closure changes its captured state between calls.
async fn run_twice<F>(mut f: F)
where
F: AsyncFnMut(),
{
f().await;
f().await;
}
async fn demo() {
let mut count = 0;
run_twice(async || {
count += 1;
})
.await;
assert_eq!(count, 2);
}Two details matter here. The parameter must be declared mut f, just as with FnMut. And each call borrows f mutably for as long as the returned future lives. You must finish awaiting the first future, or drop it, before you can make the second call. This version does not compile:
async fn broken<F>(mut f: F)
where
F: AsyncFnMut(),
{
let a = f();
let b = f(); // error: cannot borrow `f` as mutable more than once
a.await;
b.await;
}The error is not a limit of the traits. It protects the captured state from two futures mutating it at once.
AsyncFnOnce: consuming the closure
Use AsyncFnOnce when the callee needs only one call. This is the most permissive bound for callers, because the closure may move captured values out of itself.
async fn run_once<F>(f: F) -> usize
where
F: AsyncFnOnce() -> usize,
{
f().await
}
async fn demo() {
let name = String::from("hello");
let len = run_once(async move || {
let owned = name; // moves out of the closure's state
owned.len()
})
.await;
assert_eq!(len, 5);
}Moving name out of the closure's captured state makes the closure callable once. It implements AsyncFnOnce and nothing stronger. Passing it to a function that requires AsyncFn or AsyncFnMut is a compile error.
Choosing the bound in your own function
Ask what your function does with the closure, and request the weakest trait that covers it. A weaker bound accepts more callers.
Two examples. A retry helper that calls the operation again after each failure uses AsyncFnMut, because attempts run one after another. A function that runs a closure once per item concurrently uses AsyncFn, because the futures overlap.
Borrowed arguments
The main reason these bounds exist is arguments that the future borrows. A bound such as F: AsyncFn(&str) accepts a closure whose future holds on to the &str, for any lifetime of that reference.
async fn for_each_line<F>(lines: &[String], f: F)
where
F: AsyncFn(&str),
{
for line in lines {
f(line.as_str()).await;
}
}
async fn demo() {
let lines = vec![String::from("a"), String::from("b")];
for_each_line(&lines, async |line| {
println!("{line}");
})
.await;
}With the old F: Fn(&str) -> Fut shape, Fut is one fixed type chosen before the lifetime of &str is known. The future cannot mention that lifetime, so the borrow cannot flow through. The AsyncFn sugar ties the future's type to the argument's lifetime for you. The next chapter covers how the captures and arguments are borrowed in more detail.
Existing closures and functions still work
Any callable that returns a future satisfies an AsyncFn bound. A plain closure that returns an async block and a named async fn both qualify.
async fn plus_one(x: u32) -> u32 {
x + 1
}
async fn apply<F>(f: F, n: u32) -> u32
where
F: AsyncFn(u32) -> u32,
{
f(n).await
}
async fn demo() {
assert_eq!(apply(plus_one, 1).await, 2);
assert_eq!(apply(|x| async move { x * 2 }, 4).await, 8);
}If you are writing a library function, switching its bound from Fn(...) -> Fut to AsyncFn(...) therefore does not lock out callers who still write the older form. The reverse does not hold. A closure written as async |x| ... that borrows from its own captures cannot be passed to a Fn(...) -> Fut bound.
Common errors
- Missing
muton the parameter. Calling anAsyncFnMutvalue requiresmut f. The error message says you cannot borrowfas mutable. - Two outstanding futures from
AsyncFnMut. Await or drop the first future before calling again, or relax the design to useAsyncFnif the closure only reads. - Moving out of a capture while the callee needs
AsyncFn. The closure isAsyncFnOnceonly. Either clone the value inside the body, or change the bound toAsyncFnOnceif the callee calls it once. - Forgetting the output arrow.
F: AsyncFn(u32)produces a future withOutput = (). Add-> u32when the future must produce a value. - Expecting a
Sendfuture. See the warning below.
Summary of the rules
- Pick the bound by how your function calls the closure: once, in sequence, or with overlapping futures.
- Put the output after the arrow, as in
AsyncFn(u32) -> u32. The arrow describes the awaited result. - Declare the parameter
mutforAsyncFnMut. - Use
AsyncFnbounds when the future must borrow from an argument or from the closure's captures. - Fall back to
Fn(...) -> Futonly when you must bound the future itself, for example withSend.
Exercise
You are writing retry, which calls an async operation up to three times, one attempt after another, and stops at the first success. Callers want to pass closures that increment an attempt counter they own. Which bound should retry put on the closure, and why not AsyncFn?
Show answer
Use AsyncFnMut. Attempts never overlap, so exclusive access is enough, and the closure needs to mutate its captured counter. AsyncFn would reject a closure that mutates a capture, because it requires the closure to be callable through a shared reference.
Exercise
This function does not compile. Name the error and give two fixes. async fn pair<F>(mut f: F) -> u32 where F: AsyncFnMut(u32) -> u32, { let a = f(1); let b = f(2); a.await + b.await }
Show answer
The second call needs a mutable borrow of f while the future a still holds the first one, so the compiler reports a second mutable borrow. One fix is to await each call before making the next: let a = f(1).await; let b = f(2).await; a + b. The other fix is to change the bound to AsyncFn(u32) -> u32 and drop mut, which allows both futures to be alive at once, provided callers pass a closure that only reads its captures.