Sub topic 11
Trait objects and async methods: manual boxed futures
This chapter assumes you can write a trait with generics, you know what dyn Trait means, and you have used async/.await with Pin and Future at a basic level. It also assumes you read the earlier chapter on declaring async fn in traits and on Send bounds.
Why `async fn` in a trait blocks `dyn Trait`
A trait object such as Box<dyn Handler> calls methods through a vtable. A vtable is a table of function pointers, one per method. Every entry has a single fixed signature, including a single return type with a known size.
An async fn in a trait returns an anonymous future type. Each implementation produces a different one, with a different size and different internal state. The compiler cannot write one vtable entry that returns "whatever this impl's future is".
This code does not compile:
trait Handler {
async fn handle(&self, req: &str) -> String;
}
struct Echo;
impl Handler for Echo {
async fn handle(&self, req: &str) -> String {
req.to_string()
}
}
fn takes_object(_h: &dyn Handler) {}The compiler reports an error like this:
error[E0038]: the trait `Handler` is not dyn compatible"Dyn compatible" is the current name for what older documentation calls "object safe". The same limit applies to a method written as fn f(&self) -> impl Future<Output = T>. Both forms hide a different concrete type per implementor.
The fix is to give every implementation the same return type. That type must be a pointer to a future whose concrete type is erased: Pin<Box<dyn Future<Output = T> + ...>>.
The manual boxed-future signature
Here is the trait from the topic plan with a complete signature:
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) {}Each part of the return type has a job:
Box<dyn Future<...>>erases the concrete future type. The box has a known size (one pointer, or two for a fat pointer), so the vtable entry has a fixed signature.Pin<...>is needed because a future may hold references into itself once polled. Calling.awaiton a pinned box works becausePin<Box<F>>implementsFuture.Sendis a promise that the future can move between threads. Without it, the future cannot be passed totokio::spawnon a multithreaded runtime.'alets the future hold borrows. Both&'a selfandreq: &'a struse the same'a, so the async block may use either.
Implementors cannot write async fn handle in their impl block for this trait. The trait promises a Pin<Box<...>>, and an async fn returns a different type. They write an ordinary fn that returns Box::pin(async move { ... }).
The lifetime gotcha
You might try to shorten the signature using elision:
use std::future::Future;
use std::pin::Pin;
trait Handler {
fn handle(&self, req: &str) -> Pin<Box<dyn Future<Output = String> + Send + '_>>;
}When a method has &self, an elided output lifetime ('_) is tied to self only. The boxed future then cannot borrow req, and an async move block that uses req fails to compile. Name the lifetime explicitly, as in the earlier example, whenever the future uses an argument by reference.
Alternatively, make the future own its data. Take req: String, or clone what you need before building the block. The signature is then simpler, but you pay for an allocation or copy.
Using the trait object
The following program is complete. It uses a minimal block_on so that it needs no runtime crate. Waker::noop is stable since Rust 1.85, and the loop is only suitable for futures that finish without waiting on I/O.
use std::future::Future;
use std::pin::{pin, Pin};
use std::task::{Context, Poll, Waker};
trait Handler: Send + Sync {
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() })
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
fn main() {
let handlers: Vec<Box<dyn Handler>> = vec![Box::new(Echo), Box::new(Shout)];
for handler in &handlers {
println!("{}", block_on(handler.handle("hello")));
}
}The program prints hello and then HELLO. The Vec holds two different types behind one trait, which is the reason to use trait objects at all. The Send + Sync supertraits let you share Box<dyn Handler> across threads. They are separate from the Send bound on the future.
Keeping both: an `async fn` trait plus a dyn adapter
Writing Box::pin in every implementation is tedious. A common pattern is to keep your main trait ergonomic, with async fn for implementors, and add a second, dyn-compatible trait. A blanket impl connects the two, so implementors never write the boxing themselves.
The main trait declares its method as -> impl Future<Output = ...> + Send. This is the desugared form from the earlier chapter. Implementors can still write async fn, and the compiler checks that the future is Send. The adapter needs that guarantee, because it boxes the future as dyn Future + Send.
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
trait Storage {
fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;
}
trait DynStorage: Send + Sync {
fn get_boxed<'a>(
&'a self,
key: &'a str,
) -> Pin<Box<dyn Future<Output = Option<String>> + Send + 'a>>;
}
impl<T: Storage + Send + Sync> DynStorage for T {
fn get_boxed<'a>(
&'a self,
key: &'a str,
) -> Pin<Box<dyn Future<Output = Option<String>> + Send + 'a>> {
Box::pin(Storage::get(self, key))
}
}
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
async fn lookup(store: &dyn DynStorage, key: &str) -> String {
store.get_boxed(key).await.unwrap_or_default()
}Generic code can take S: Storage and avoid allocation. Code that needs runtime selection, such as a plugin list or a handler chosen from configuration, takes &dyn DynStorage. The two traits use different method names (get and get_boxed) so a type that implements both never has an ambiguous call.
Trade-offs
| Approach | Dyn compatible | Allocation per call | Implementor writes |
|---|---|---|---|
| `async fn` in trait | No | None | `async fn` |
| `-> impl Future + Send` in trait | No | None | `async fn` or `fn` |
| Manual `Pin<Box<dyn Future>>` | Yes | One `Box` | `Box::pin(async move { ... })` |
| `async fn` trait plus dyn adapter | Only the adapter | One `Box` on the dyn path | `async fn` |
Keep these failure modes in mind:
- Allocation cost. Each call allocates a box. For a handler that does network I/O this is negligible. In a tight loop over millions of cheap calls it can show up in a profile.
- Choosing
Sendin the signature. If you leaveSendout, no implementation can be spawned on a multithreaded executor. If you include it, implementations that hold a non-Sendvalue across an.awaitfail to compile. Pick based on your executor. Single-threaded executors do not need it. - Borrow conflicts. The future borrows
selfand the arguments for'a. You cannot mutate or drop them while the future is alive. This is the same rule as for any borrow, but the boxed future makes it easy to store the future somewhere and forget it holds a reference. 'staticdefault. InBox<dyn Handler>, the trait object has an implicit'staticbound. A handler that holds a borrowed reference needsBox<dyn Handler + 'a>.
Exercises
Exercise
A colleague writes trait Job { async fn run(&self) -> u32; } and then let jobs: Vec<Box<dyn Job>> = Vec::new();. Why does this fail, and what return type would make the trait dyn compatible?
Show answer
Each implementation of run returns a different anonymous future type, so the vtable cannot give run a single return type. Declaring fn run<'a>(&'a self) -> Pin<Box<dyn Future<Output = u32> + Send + 'a>> gives every implementation the same type: a pinned box of a type-erased future. Implementors then write Box::pin(async move { ... }).
Exercise
You declare fn handle(&self, req: &str) -> Pin<Box<dyn Future<Output = String> + Send + '_>> and implement it with Box::pin(async move { req.to_string() }). The compiler rejects it with a lifetime error. What is wrong and how do you fix it?
Show answer
With &self present, the elided '_ in the return type is tied to self only, not to req. The async block borrows req, so the future may outlive that borrow. Name one lifetime and use it for all three: fn handle<'a>(&'a self, req: &'a str) -> Pin<Box<dyn Future<Output = String> + Send + 'a>>. You could also take req: String so the future owns its data.