Sub topic 6
Accepting async closures with AsyncFn, AsyncFnMut, and AsyncFnOnce
This chapter assumes you know the Fn, FnMut, and FnOnce traits, basic async/await, and generic trait bounds. You have seen that async |x| ... creates an async closure. Now you will learn how to write a function that accepts one.
The three traits
Rust 1.85 added three traits that mirror the closure traits. Each one describes how the closure is called and whether the future it returns can borrow from the closure.
| Trait | Call takes | Can be called | Typical use |
|---|---|---|---|
| `AsyncFn` | `&self` | many times, even concurrently | read-only callbacks |
| `AsyncFnMut` | `&mut self` | many times, one at a time | callbacks that update state |
| `AsyncFnOnce` | `self` | once | callbacks that consume captured values |
The traits form a hierarchy, just like the closure traits. Anything that implements AsyncFn also implements AsyncFnMut, and anything that implements AsyncFnMut also implements AsyncFnOnce. As a caller, ask for the weakest trait you need. That accepts the most closures.
Bound syntax
You write the bound like a Fn bound. The arguments go in parentheses, and the -> T part is the output of the future, not the future itself.
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);
}There is no Fut type parameter. The old pattern needed F: Fn(u32) -> Fut, Fut: Future<Output = u32>. The AsyncFn bound replaces both.
AsyncFnMut: calling repeatedly with state
If the closure changes a captured variable, use AsyncFnMut. The parameter must be declared mut, because each call borrows the closure mutably.
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);
}Each f().await finishes before the next call starts. This matters because the future from one call holds a mutable borrow of the closure.
AsyncFnOnce: consuming captures
If the closure moves a captured value out, it can only run once. Ask for AsyncFnOnce.
async fn run_once<F>(f: F) -> String
where
F: AsyncFnOnce() -> String,
{
f().await
}
async fn demo() {
let name = String::from("Ferris");
let greeting = run_once(async move || format!("hello {name}")).await;
assert_eq!(greeting, "hello Ferris");
}Borrowed arguments
The main gain over the old pattern is with borrowed arguments. A bound such as AsyncFn(&str) lets the returned future hold the borrow.
async fn for_each_line<F>(lines: &[String], f: F)
where
F: AsyncFn(&str),
{
for line in lines {
f(line).await;
}
}
async fn demo() {
let lines = vec![String::from("a"), String::from("b")];
for_each_line(&lines, async |line| {
println!("{line}");
})
.await;
}With F: Fn(&str) -> Fut, the single Fut type cannot depend on the lifetime of each call. This is the failure from the previous chapter.
Other things that satisfy the bounds
Async closures are not the only values that fit. A regular closure that returns a future also satisfies AsyncFn(u32) -> u32, and so does an async fn item. Existing callers keep working when you switch a function to the new bounds.
Common errors
- Forgetting
mut. Calling anAsyncFnMutparameter that was declared withoutmutgives a "cannot borrow as mutable" error. - Calling
AsyncFnOncetwice. The first call movesf, so a second call reports "use of moved value". - Asking for too much. Requiring
AsyncFnwhen you only call once rejects closures that mutate or move captures. PreferAsyncFnOnceif you call once, andAsyncFnMutif you call in sequence. - Running calls at the same time. Only
AsyncFnallows several calls whose futures are alive together, for example withjoin. AnAsyncFnMutcall needs the previous future to be finished or dropped.
Exercise
You write a function that calls a callback exactly once per item, one item after another, and the callback pushes each item into a captured Vec. Which bound should the callback parameter use, and does the parameter need mut?
Show answer
Use AsyncFnMut(Item). The callback mutates captured state and is called several times in sequence. AsyncFn would reject the closure because it mutates captured state, and AsyncFnOnce would allow only one call. The parameter must be declared mut f, because each call borrows the closure mutably.