Sub topic 13
Choosing the Right Tool
This chapter ties the previous ones together. It gives you a way to pick between async closures, closures that return async blocks, async fn in traits, manual boxed futures, and the async_trait crate. I assume you can read AsyncFn bounds, know what Send means for a future, and have seen dyn Trait before. Async closures need Rust 1.85 or later, and async fn in traits needs Rust 1.75 or later.
Two separate questions
The tools solve two different problems, so decide them separately.
- Callbacks. Does a function take a piece of async behavior as an argument? The choice is between an async closure and a closure that returns an async block.
- Abstractions. Does a type need to expose async methods through a trait? The choice is between
async fnin a trait,-> impl Future + Send, a manual boxed future, andasync_trait.
Most code has only one of these problems at a time.
Choosing for callbacks
Default to an async closure with an AsyncFn, AsyncFnMut, or AsyncFnOnce bound. The bound lets the returned future borrow from the closure's captures and from its arguments. It also removes the extra Fut type parameter.
Pick the bound by how the callee calls the closure:
AsyncFnOnceif the callee calls it once.AsyncFnMutif the callee calls it several times, one call at a time, and the closure may mutate captured state.AsyncFnif the callee calls it several times and may call it while an earlier future is still alive.
Ask for the weakest bound that works. A callee that needs AsyncFn when AsyncFnMut would do rejects callers whose closures mutate state.
The closure-returns-async-block pattern still has a place in these cases:
- Older compilers. Your minimum supported Rust version is below 1.85.
- You must name the future. You need
Fut: Send, you store the future, or you pass it to a spawn function. TheAsyncFnfamily has no stable way to say that the returned future isSend. A bound likeF: Fn(u32) -> Fut, Fut: Future + Send + 'staticstates it directly. - Type erasure. You store callbacks as
Box<dyn Fn(Req) -> Pin<Box<dyn Future<Output = Resp> + Send>>>. This is the same boxed-future technique used for trait objects, applied to closures.
A closure that returns a future also satisfies an AsyncFn bound. Callers who already have the old style keep working when you migrate your API to AsyncFn. The reverse does not hold. An async closure whose future borrows from its own captured state cannot satisfy an Fn(..) -> Fut bound, because Fut cannot name a borrow of the closure itself.
Choosing for traits
Start with plain async fn in the trait. It is the simplest form and works well when the trait is used through generics (S: Store) and the executor is single-threaded or you never need to move the futures between threads.
Move to a different form when one of these constraints appears:
| Situation | Use | Cost |
|---|---|---|
| Generic code only, no `Send` needed | `async fn` in the trait | None. Static dispatch, no allocation. |
| Generic code on a multithreaded executor | `fn m(&self) -> impl Future<Output = T> + Send` in the trait | Implementors can still write `async fn`, but their futures must be `Send` or the impl fails to compile. |
| Trait is `pub` and downstream crates implement or call it | `-> impl Future + Send`, or a generated `Send` variant | Avoids the `async_fn_in_trait` lint, which warns that callers cannot add `Send` bounds. |
| Need `dyn Trait` and want to see exactly what happens | Manual `Pin<Box<dyn Future + Send + '_>>` return type | One heap allocation per call, and more verbose signatures. |
| Need `dyn Trait` across many methods or many implementors | The `async_trait` crate | One heap allocation per call, a macro on the trait and every impl. |
| Need `dyn Trait` and the set of types is closed | An enum that implements the trait by matching on its variants | No allocation, but you maintain the enum. |
Three details are easy to miss.
async fnin a trait is not dyn compatible. Each implementation returns a different anonymous future type, so the compiler cannot build a vtable entry for it. A boxed future has one fixed type,Pin<Box<dyn Future>>, which is why the manual andasync_traitapproaches work.Sendis a property of the whole future. Anasync fnin a trait leaves theSendquestion open for generic callers. A generic function likeload<S: Store>is onlySendif the trait method's future is guaranteedSend. The-> impl Future + Sendform writes that guarantee into the trait.async_traitaddsSendby default. It requiresSendfutures unless you write#[async_trait(?Send)]. That default matches multithreaded runtimes but breaks implementations that holdRcor other non-Sendvalues across an.await.
The crates trait_variant and dynosaur also exist in the ecosystem. The first generates a Send version of a trait from one definition. The second generates a dyn-compatible wrapper around an async fn trait. Check their documentation for current attributes before you adopt them, since this part of the ecosystem is still changing.
A decision flow
A worked example
This program uses one choice from each side. retry takes a callback that mutates state, so it uses AsyncFnMut. The Store trait is used generically on a multithreaded executor, so it declares impl Future + Send. The block_on helper uses Waker::noop, stable since Rust 1.85, so the example runs without an external runtime. It only works for futures that never actually wait, which is true here.
use std::collections::HashMap;
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
trait Store {
fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;
}
struct Mem(HashMap<String, String>);
impl Store for Mem {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
async fn load<S: Store + Sync>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}
async fn retry<F>(attempts: u32, mut op: F) -> Result<u32, String>
where
F: AsyncFnMut(u32) -> Result<u32, String>,
{
let mut last = Err(String::from("no attempts"));
for n in 1..=attempts {
last = op(n).await;
if last.is_ok() {
break;
}
}
last
}
fn require_send<T: Send>(_value: T) {}
fn main() {
let mem = Mem(HashMap::from([(String::from("a"), String::from("alpha"))]));
let mut log = Vec::new();
// Compiles only because Store::get promises a Send future.
require_send(load(&mem, "a"));
let (found, result) = block_on(async {
let found = load(&mem, "a").await;
let result = retry(3, async |n| {
log.push(n);
if n < 3 {
Err(format!("attempt {n} failed"))
} else {
Ok(n * 10)
}
})
.await;
(found, result)
});
println!("found = {found}");
println!("result = {result:?}");
println!("log = {log:?}");
}The program prints found = alpha, result = Ok(30), and log = [1, 2, 3]. The closure passed to retry pushes into log, which lives outside it. That is the case where a closure returning an async block would fail, because the future would borrow from the closure's captured &mut state.
Common mistakes
- Using
AsyncFnwhenAsyncFnMutorAsyncFnOncewould do. This rejects callers for no reason. - Writing
F: AsyncFn(..)and then trying to move the returned future into a spawn function that needsSend + 'static. Switch to theFn(..) -> Futform with explicit bounds, or call the closure inside an already-spawned task. - Declaring
-> impl Future + Sendand then implementing the method with anasync fnthat holds anRcor aMutexGuardfromstdacross an.await. The impl is rejected because its future is notSend. - Adding
async_traitto a trait that is only used generically. It boxes every call for no benefit. - Using
dyn Traitwith plainasync fnmethods and expecting a fix from a lifetime annotation. The limit is dyn compatibility, so you need boxed futures,async_trait, or an enum.
Exercise
You are writing for_each_line, which calls a user-supplied async callback once per line and passes it a &str borrowed from the line. The callback may push into a Vec it captures. Which bound do you write, and why not Fn(&str) -> Fut?
Show answer
Write F: AsyncFnMut(&str). The callback is called many times in sequence and mutates captured state, so AsyncFnMut is the weakest bound that fits. A Fn(&str) -> Fut bound uses one Fut type for every call, so it cannot express a future that borrows from the particular &str argument. It also cannot express a future that borrows from the closure's mutable captures.
Exercise
A library defines pub trait Cache { async fn get(&self, k: &str) -> Option<String>; } and users run it under a multithreaded executor that requires Send futures. What problem will they hit, and what is the fix that keeps async fn in implementations?
Show answer
Generic code over C: Cache cannot prove the future returned by get is Send, so it cannot be passed to a spawn function. The compiler also warns about this on public traits with the async_fn_in_trait lint. Declare the method as fn get(&self, k: &str) -> impl Future<Output = Option<String>> + Send; in the trait. Implementors can still write async fn get(..), as long as their future is Send.
Exercise
You have a plugin system where the program holds Vec<Box<dyn Plugin>> and each plugin has async methods. List two ways to make this work and one cost they share.
Show answer
Return Pin<Box<dyn Future<Output = T> + Send + '_>> from each method by hand, or put #[async_trait] on the trait and each impl. If the plugin set is fixed, an enum that implements Plugin also works. The two boxing approaches share the cost of one heap allocation per method call.