Sub topic 2
Writing Async Closures
This chapter assumes basic Rust ownership, borrowing, lifetimes, closures, Future, and async/await. It also assumes you can define traits and use generic trait bounds.
Writing async closures
An async closure is a closure whose call produces a future:
async fn add_offset() {
let offset = 10;
let add = async |value: u32| value + offset;
assert_eq!(add(5).await, 15);
}The async keyword belongs before the closure parameters. The closure body can use .await, and calling the closure does not run it immediately. Calling it creates a future; .await runs that future.
Async closures are useful when a function needs to receive asynchronous behavior from its caller.
Accepting async closures with `AsyncFn`
Rust provides three async closure traits:
AsyncFnsupports repeated calls without mutation.AsyncFnMutsupports repeated calls that may mutate captured state.AsyncFnOncesupports a call that consumes the closure.
async fn apply<F>(f: F, value: u32) -> u32
where
F: AsyncFn(u32) -> u32,
{
f(value).await
}
async fn demo() {
let offset = 10;
let result = apply(async |value| value + offset, 5).await;
assert_eq!(result, 15);
}For a mutable closure, use AsyncFnMut and make the parameter mutable:
async fn twice<F>(mut f: F)
where
F: AsyncFnMut(),
{
f().await;
f().await;
}Use AsyncFnOnce when the operation consumes captured values or should run only once.
Borrowing captures and arguments
Async closures can return futures that borrow from their captures or arguments. This avoids some limits of the older pattern, |x| async move { ... }, where each call often needs one fixed future type.
async fn print_lines<F>(lines: &[String], f: F)
where
F: AsyncFn(&str),
{
for line in lines {
f(line).await;
}
}The future created for each call may hold the borrowed &str until it finishes. The caller must therefore keep lines alive while the future is being awaited.
Async functions in traits
Since Rust 1.75, traits can declare async methods directly:
use std::collections::HashMap;
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
struct MemoryStore(HashMap<String, String>);
impl Storage for MemoryStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
async fn lookup<S: Storage>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}Each implementation supplies its own future type. Generic code can call the method normally with .await.
Exercise
Which bound should a function use when it must call an async closure twice and the closure mutates captured state?
Show answer
Use AsyncFnMut, and bind the closure parameter as mut.