Sub topic 19
async fn in traits
This chapter assumes you know how async fn returns a future, how .await and tokio::spawn work, and the basics of traits, generics, and Send. Since Rust 1.75, a trait can declare async fn methods directly. The syntax is simple, but there are limits around Send and trait objects.
Declaring and implementing an async method
You write async fn in the trait and in each impl, exactly as you would in a free function.
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);
}A trait method can also have a default body that is async. Impls can override it or inherit it.
Before 1.75, this required the async-trait crate or hand-written boxed futures. The compiler now does the work without boxing, so a call through a concrete type or a generic parameter allocates nothing extra.
What the compiler turns it into
An async fn in a trait is shorthand for a method that returns an anonymous future. The trait above is roughly equivalent to this:
use std::future::Future;
trait Fetcher {
fn fetch(&self, id: u32) -> impl Future<Output = String>;
}The impl Future in return position of a trait method is called return-position impl Trait in traits (RPITIT). Each impl gets its own concrete future type, and it borrows from &self for as long as the future lives.
This explains the two main limits, which the next sections cover. The future's type is unknown to the caller, so the caller cannot see whether it is Send. The return type also differs from impl to impl, so the compiler cannot build a single vtable entry for it.
The Send problem
tokio::spawn requires the spawned future to be Send. If you call a trait's async method from a generic function, the compiler knows only what the trait promises. Plain async fn in a trait promises nothing about Send.
use std::future::Future;
trait Fetcher {
async fn fetch(&self, id: u32) -> String;
}
async fn fetch_in_task<F>(fetcher: F, id: u32) -> String
where
F: Fetcher + Send + 'static,
{
tokio::spawn(async move { fetcher.fetch(id).await })
.await
.unwrap()
}This does not compile. The error says the future returned by fetch cannot be sent between threads safely, even though F itself is Send. The compiler cannot assume that every implementor's future is Send.
The fix is to write the method in its desugared form and add the bound yourself. Implementors may 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 fetch_in_task<F>(fetcher: F, id: u32) -> String
where
F: Fetcher + Send + 'static,
{
tokio::spawn(async move { fetcher.fetch(id).await })
.await
.unwrap()
}
#[tokio::main]
async fn main() {
println!("{}", fetch_in_task(Local, 7).await);
}The impl's async fn is checked against the + Send promise. If an implementor holds a non-Send value, such as an Rc, across an .await, that impl fails to compile. The error appears at the impl, not at the distant call site.
Trait objects are not supported
A trait with async fn is not dyn-compatible. This code fails:
trait Fetcher {
async fn fetch(&self, id: u32) -> String;
}
fn build() -> Vec<Box<dyn Fetcher>> {
Vec::new()
}The compiler reports that the trait is not dyn compatible. A dyn Fetcher would need one fixed return type for fetch, but every impl returns a different future type. Making that work requires boxing the future, which the language does not do implicitly because it allocates.
When you need runtime polymorphism, use the async-trait crate (add async-trait to Cargo.toml). It rewrites each method to return Pin<Box<dyn Future + Send>>.
use async_trait::async_trait;
#[async_trait]
trait Fetcher: Send + Sync {
async fn fetch(&self, id: u32) -> String;
}
struct Local;
struct Remote;
#[async_trait]
impl Fetcher for Local {
async fn fetch(&self, id: u32) -> String {
format!("local {id}")
}
}
#[async_trait]
impl Fetcher for Remote {
async fn fetch(&self, id: u32) -> String {
format!("remote {id}")
}
}
#[tokio::main]
async fn main() {
let sources: Vec<Box<dyn Fetcher>> = vec![Box::new(Local), Box::new(Remote)];
for s in &sources {
println!("{}", s.fetch(1).await);
}
}Each call allocates a box for the future. For I/O-bound code this cost is usually negligible. In a hot loop it may matter.
Choosing an approach
| Need | Approach | Cost |
|---|---|---|
| Generic code, you control all callers | Plain `async fn` in the trait | None |
| Generic code, callers spawn futures | `-> impl Future<Output = T> + Send` in the trait | None |
| Runtime choice among implementations | `async-trait` and `Box<dyn Trait>` | One allocation per call |
Common errors
- "future cannot be sent between threads safely" in a generic function. The trait does not promise
Send. Add+ Sendto the trait's return type, as shown above. - "the trait is not dyn compatible." You used
Box<dyn Trait>or&dyn Traitwith an async method. Switch to generics, or useasync-trait. - Mixing
#[async_trait]on the trait but not the impl. The macro must appear on both. Otherwise the signatures do not match. - Expecting a bound on
Self.Sendon the future does not follow fromSelf: Send. The future may hold other data.
Exercise
A public trait declares async fn load(&self) -> Vec<u8>;. A user writes a generic async fn spawn_load<L: Load + Send + Sync + 'static>(l: Arc<L>) that calls tokio::spawn(async move { l.load().await }), and it fails with a "cannot be sent between threads safely" error. What is the cause, and how do you fix the trait?
Show answer
The trait does not promise that the future returned by load is Send, so the compiler cannot prove the spawned future is Send, even though L is Send + Sync. Declare the method as fn load(&self) -> impl Future<Output = Vec<u8>> + Send; (with use std::future::Future;). Implementors can still write async fn load(&self) -> Vec<u8>, and the compiler checks that their future is Send.
Exercise
Why can Vec<Box<dyn Fetcher>> not be built when Fetcher uses native async fn, and what is the usual workaround?
Show answer
Each impl returns a different anonymous future type, so a dyn Fetcher vtable cannot give fetch a single return type. Native async methods do not box their futures. The usual workaround is the async-trait crate, which boxes each returned future as Pin<Box<dyn Future + Send>> so the trait becomes dyn-compatible, at the cost of one allocation per call.