Sub topic 18
async fn in traits
This chapter assumes you know traits and generics, async fn, .await, and tokio::spawn with its Send and 'static requirements.
What changed in Rust 1.75
Before Rust 1.75, a trait could not contain an async fn. Programs worked around this with the async-trait crate, which boxed every future. Now you can write async fn directly in a trait and in its implementations:
trait Fetcher {
async fn fetch(&self, id: u32) -> String;
}
struct Local;
impl Fetcher for Local {
async fn fetch(&self, id: u32) -> String {
format!("item {id}")
}
}
#[tokio::main]
async fn main() {
println!("{}", Local.fetch(7).await);
}Nothing is boxed. The compiler treats the method as returning an anonymous future type, so calls through a concrete type or a generic parameter can be fully inlined.
What the signature means
async fn fetch(&self, id: u32) -> String in a trait is shorthand for a method that returns impl Future<Output = String>. That future borrows &self, so it cannot outlive the borrow.
This desugaring explains the two main limits.
Gotcha 1: the future is not known to be Send
When you call the method on a concrete type such as Local, the compiler sees the real future and can tell whether it is Send. In generic code it only sees "some future", and it assumes nothing. A generic function that passes such a future to tokio::spawn then fails with an error saying the future cannot be sent between threads safely.
To fix this, declare the method in the trait with an explicit Send bound. Implementations can still use async fn:
use std::future::Future;
trait Fetcher {
fn fetch(&self, id: u32) -> impl Future<Output = String> + Send;
}
struct Local;
impl Fetcher for Local {
async fn fetch(&self, id: u32) -> String {
format!("item {id}")
}
}
async fn run<F>(f: F) -> String
where
F: Fetcher + Send + Sync + 'static,
{
tokio::spawn(async move { f.fetch(1).await })
.await
.unwrap()
}
#[tokio::main]
async fn main() {
println!("{}", run(Local).await);
}The compiler checks each implementation against the bound. If an implementation's future holds a non-Send value across an .await, it reports an error at that implementation.
Gotcha 2: no trait objects
A trait with an async fn is not dyn compatible. Box<dyn Fetcher> does not compile, because each implementation returns a future of a different size and dyn needs one fixed return type.
You have three options:
- Use generics (
F: Fetcher) and accept one compiled copy per type. - Use an enum that wraps the possible implementations.
- Keep the
async-traitcrate for that trait. It boxes the futures, which makes the trait dyn compatible at the cost of one allocation per call.
| Need | Choice |
|---|---|
| Static dispatch, no allocation | Native `async fn` in the trait |
| Callers spawn the futures | Native, with `-> impl Future + Send` |
| `Box<dyn Trait>` | `async-trait` crate |
Exercise
A generic function run<F: Fetcher>(f: F) calls tokio::spawn(async move { f.fetch(1).await }), where fetch is declared as async fn in the trait. The build fails with a "future cannot be sent between threads safely" error. What do you change, and why?
Show answer
Declare the method in the trait as fn fetch(&self, id: u32) -> impl Future<Output = String> + Send;. In generic code the compiler cannot see the concrete future, so it cannot prove the future is Send, and spawn requires it. The explicit bound guarantees it. Implementations can still be written with async fn, and the compiler checks each one against the bound. You may also need F: Send + Sync + 'static.