Sub topic 13
Choosing the right tool
This chapter assumes you know closures and the Fn traits, can write basic async/await code, and understand trait bounds. It does not introduce new syntax. It helps you pick between the options from the earlier chapters.
Choosing for callbacks
Your function takes a callback that returns a future. Three designs are possible.
| Situation | Use | Column | Column |
|---|---|---|---|
| The callback receives borrowed arguments, or mutates or borrows captured state | An async closure with an `AsyncFn`, `AsyncFnMut`, or `AsyncFnOnce` bound | ||
| The callback runs once | `AsyncFnOnce` | ||
| You must support Rust older than 1.85 | `Fn(A) -> Fut` with `Fut: Future`, and callers pass `\ | x\ | async move { ... }` |
| You need to require that the returned future is `Send` | `Fn(A) -> Fut` with `Fut: Future + Send` |
In new code, start with AsyncFn. The bound has one parameter fewer, and the future can borrow from the closure and from its arguments. Fall back to the older pattern when you need to name the future type. For example, you may need to add Send to it. An AsyncFn bound gives you no simple way to name the returned future.
Pick the weakest bound the callee needs. Use AsyncFnOnce if you call it once, AsyncFnMut if you call it repeatedly in sequence, and AsyncFn only if calls may overlap or the closure must not change.
Choosing for traits
The questions for a trait with async methods are about threads and trait objects.
Plain async fn in a trait is right when the trait is internal and its callers are generic. Whether the future is Send is then checked on the concrete type, so no extra work is needed.
For a public trait, or any trait used with tokio::spawn-style executors, write the method as fn name(&self) -> impl Future<Output = T> + Send. The Send guarantee becomes part of the contract. Implementors can still write async fn, and the compiler rejects an implementation whose future is not Send. This is also why the compiler warns about plain async fn in public traits: callers cannot add the bound afterwards.
use std::future::Future;
trait Fetcher {
fn fetch(&self, id: u64) -> impl Future<Output = String> + Send;
}
struct Local;
impl Fetcher for Local {
async fn fetch(&self, id: u64) -> String {
format!("item {id}")
}
}
fn run<F: Fetcher + Sync>(f: &F) -> impl Future<Output = String> + Send + '_ {
async move { f.fetch(1).await }
}
async fn demo() {
assert_eq!(run(&Local).await, "item 1");
}run returns a Send future only because fetch promises one. With a plain async fn fetch in the trait, this function would fail to compile.
Trait objects
dyn Trait does not work with async fn methods, because each implementation returns a different future type. You have two workarounds:
- Manual boxing. Return
Pin<Box<dyn Future<Output = T> + Send + 'a>>. This has no dependencies and the cost is visible, but every implementor writesBox::pin(async move { ... }). It suits a small trait with a few methods. - The
async_traitcrate. The attribute macro does the boxing for you and keeps theasync fnsyntax. It suits many methods or many implementors. It allocates on every call, and it adds aSendbound by default.
If only some call sites need dynamic dispatch, consider an enum over the concrete types. It avoids both the box and the macro.
Exercise
A library exposes trait Cache { async fn get(&self, k: &str) -> Option<String>; }. Users complain they cannot call it inside tokio::spawn. What change fixes this, and does it break existing implementors who write async fn get?
Show answer
Change the declaration to fn get(&self, k: &str) -> impl Future<Output = Option<String>> + Send;. Implementors can keep writing async fn get. The compiler accepts them as long as their future is Send. Any implementor whose future holds a non-Send value across an .await will now fail to compile, which is the intended check.
Exercise
You are writing fn retry<F>(f: F) that calls an async callback with a &str argument and the closure mutates a counter. Which bound do you choose, and why not Fn(&str) -> Fut?
Show answer
Use F: AsyncFnMut(&str), because the closure mutates captured state across calls. With Fn(&str) -> Fut and a single generic Fut, the future cannot borrow from the &str argument, and a closure that mutates captures does not satisfy Fn.