Sub topic 11
Trait objects and async methods: manual boxed futures
This chapter assumes you know how to define traits with generics, how dyn Trait works at a basic level, and what Pin and Box do. It builds on the previous chapters on async fn in traits and how it desugars to -> impl Future.
Why async fn in traits is not dyn compatible
A trait object (dyn Trait) hides the concrete type behind a pointer and a vtable. The vtable holds one function pointer per method, and every entry must have a fixed signature the compiler knows without seeing the implementor.
An async fn in a trait desugars to a method that returns impl Future<Output = T>. Each implementation returns its own anonymous future type, and each of those types has a different size. A vtable entry cannot name "some future of unknown size", so the compiler rejects the trait as a trait object.
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
// error: the trait `Storage` is not dyn compatible
// fn use_it(_s: &dyn Storage) {}The fix is to give every implementor the same return type. A boxed, pinned future does that, because Pin<Box<dyn Future<Output = T> + '_>> is a pointer with a known size.
Writing the boxed future by hand
Change the method signature so it returns a boxed future, and box the async block inside each implementation.
use std::future::Future;
use std::pin::Pin;
trait Handler {
fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>;
}
struct Echo;
impl Handler for Echo {
fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>> {
Box::pin(async move { req.to_string() })
}
}
fn takes_object(_h: &dyn Handler) {}Three parts of the signature matter:
Pin<Box<...>>gives a fixed-size pointer.Pinis required because futures may be self-referential once polled.+ Sendmakes the future usable on multithreaded executors. Drop it if you never move these futures across threads.'aties the future to both&selfandreq. The async block borrows both, so the future cannot outlive either.
Calling the method looks the same as before:
use std::future::Future;
use std::pin::Pin;
trait Handler {
fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>;
}
struct Echo;
struct Shout;
impl Handler for Echo {
fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>> {
Box::pin(async move { req.to_string() })
}
}
impl Handler for Shout {
fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>> {
Box::pin(async move { req.to_uppercase() })
}
}
async fn run_all(handlers: &[Box<dyn Handler>], req: &str) -> Vec<String> {
let mut out = Vec::new();
for h in handlers {
out.push(h.handle(req).await);
}
out
}run_all accepts a mix of Echo and Shout in one slice. That is the reason to pay for dynamic dispatch.
Costs and common errors
Boxing has a price. Each call allocates on the heap, and polling goes through a vtable. For a network handler this is usually negligible. For a tight loop that calls a tiny async method millions of times, measure first.
Common errors:
- Missing
move. Withoutasync move, the block borrowsreqas a local reference to a parameter that is dropped whenhandlereturns. Addmoveso the block takes ownership of the references. - Wrong lifetime. Writing
Box<dyn Future<Output = String> + Send>without a lifetime defaults to'static. The borrow of&selfthen fails to compile. Add+ 'aand tie it to the arguments. - Forgetting
Sendin the trait. If an implementation holds a non-Sendvalue across an.await, the compiler reports the error at theBox::pinline. - Using
async fnin the impl. The impl signature must match the trait's boxed return type, so you cannot writeasync fn handlethere.
Exercise
Why does a trait with async fn get(&self) -> u32 fail to compile when you write &dyn Trait, and what return type makes it work?
Show answer
Each implementation of async fn returns a different anonymous future type with its own size, so a vtable entry cannot describe the return type. Declaring the method as fn get<'a>(&'a self) -> Pin<Box<dyn Future<Output = u32> + Send + 'a>> gives every implementation the same fixed-size return type, and the trait becomes dyn compatible.
Exercise
In a Handler impl, you write Box::pin(async { req.to_string() }) and get a borrow error. What is the likely fix?
Show answer
Use async move { ... }. Without move, the block borrows the local parameter req itself, which does not live as long as the returned future. With move, the block takes the reference by value, and the lifetime 'a on the signature keeps it valid.