Sub topic 3
What async fn in a trait desugars to
Assume basic Rust ownership, lifetimes, traits, generics, and async/await. This chapter focuses on how async trait methods are represented and when their limitations matter.
Return-position futures
An async fn returns a lazy future. In a trait, Rust hides that future's concrete type with return-position impl Trait:
trait Fetcher {
async fn fetch(&self, id: u64) -> String;
}Conceptually, this is similar to:
use std::future::Future;
trait Fetcher {
fn fetch(&self, id: u64) -> impl Future<Output = String> + '_;
}The '_ means the future may borrow from self or other arguments. Each implementation can use a different anonymous future type.
Making trait method futures `Send`
A future is Send when it can safely move between threads. Multithreaded executors often require this guarantee.
An async fn in a trait does not promise Send by default. Write the equivalent return type when the promise belongs in the trait:
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}")
}
}The implementation's async method satisfies the trait's Send requirement.
> callout note > A future can be non-Send if it holds a non-Send value across an .await. Add Send only when the executor or API requires it.
Trait objects and boxed futures
Traits containing async fn are not dyn compatible. You cannot use &dyn Fetcher directly. A manually boxed future provides a fixed, dynamically dispatched type:
use std::future::Future;
use std::pin::Pin;
trait Handler {
fn handle<'a>(
&'a self,
request: &'a str,
) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>;
}
struct Echo;
impl Handler for Echo {
fn handle<'a>(
&'a self,
request: &'a str,
) -> Pin<Box<dyn Future<Output = String> + Send + 'a>> {
Box::pin(async move { request.to_owned() })
}
}Boxing adds allocation and dynamic dispatch, but supports dyn Handler.
Choosing an approach
| Need | Suitable approach |
|---|---|
| Static generic dispatch | `async fn` in a trait |
| A `Send` guarantee | `impl Future + Send` |
| Dynamic dispatch | Manually boxed future or `async_trait` |
| Simple compatibility across older patterns | `async_trait` |
The async_trait crate uses an attribute macro to generate boxed futures. Choose it when its convenience outweighs allocation and dispatch costs, or when an existing codebase already uses it. Prefer native async traits for generic code that does not need trait objects.
Exercise
Why can a trait with async fn usually not be used as dyn Trait?
Show answer
Its method returns an opaque, implementation-specific future type, so a trait object lacks one fixed method signature. Boxing the future provides that fixed type.