A Rust `Storage` trait with a native `async fn get` fails with E0038 at `Vec<Box<dyn Storage>>`: why, and what are the stable fixes?
answer
- a vtable needs one signature
- opaque return types are not dispatchable
- box the future yourself
- an erased companion trait
basics
~20 sAn async fn method returns a hidden future type that differs per implementor, and a vtable slot cannot describe it. Fixes: return Pin<Box<dyn Future>> (by hand or with async-trait), add a boxed companion trait, or use an enum.
solid answer
~50 sA trait object calls methods through a vtable, so every dispatchable method needs one fixed signature for all implementors. A native `async fn` has an opaque return type that is different for each impl, and the Reference lists `async fn` among methods that cannot be dispatched, so rustc reports E0038 "the trait `Storage` is not dyn compatible" and points at `get` being `async`. On stable you erase the type yourself: make the method return `Pin<Box<dyn Future<Output = T> + Send + '_>>` (the shape the async-trait crate generates), or keep the native trait for generic code and add a dyn-compatible companion trait with a blanket impl that boxes the future. A closed set of backends can use an enum instead. `where Self: Sized` on the method keeps the trait dyn-compatible but removes `get` from the trait object.
code
rust · 11 linestrait Storage {
async fn get(&self, key: &str) -> Option<Vec<u8>>;
}
struct RamStore;
impl Storage for RamStore {
async fn get(&self, _key: &str) -> Option<Vec<u8>> { None }
}
fn main() {
let stores: Vec<Box<dyn Storage>> = vec![Box::new(RamStore)];
let _ = stores.len();
}go deeper
Recall that a trait with an async fn method cannot be used as Box<dyn Trait> and that rustc reports E0038 for it.
Explain the vtable argument: each impl returns a different hidden future type, and one function-pointer slot cannot return many types.
Pick the fix by call pattern: hand-boxed or async-trait signatures, an erased companion with a blanket impl, or an enum, and know where Self: Sized is not a fix.
Decide where the boxing cost lands in a codebase, keeping hot generic paths unboxed and isolating dynamic dispatch at the plugin boundary.
## The error A storage layer has an in-memory backend and a remote one, and a router wants to keep both in a `Vec<Box<dyn Storage>>`. With a native async method rustc 1.99.1 refuses (excerpt): ```plaintext error[E0038]: the trait `Storage` is not dyn compatible ... 2 | async fn get(&self, key: &str) -> Option<Vec<u8>>; | ^^^ ...because method `get` is `async` = help: consider moving `get` to another trait ``` ## Why a vtable cannot hold it A `dyn Storage` is a data pointer plus a pointer to a **vtable**, one function pointer per dispatchable method. Every entry must have one signature shared by every type behind the object. A native `async fn get` returns a **hidden future type** chosen by each implementation: the in-memory store's future and the remote store's future are different types of different sizes. The caller of `dyn Storage::get` would not know how much space the result needs or which `poll` to call. The Reference states the rule directly. A dispatchable method must not have an opaque return type, which it spells out as: - not an `async fn` (which has a hidden `Future` type); - not a return-position `impl Trait`. `&self` is a fine receiver and lifetime parameters are allowed; the return type is the only problem. Other dyn-compatibility rules, such as generic methods or returning `Self`, belong to the material on trait objects. ## The stable fixes | Fix | Generic calls | Dyn calls | Cost | |---|---|---|---| | Method returns `Pin<Box<dyn Future<Output = T> + Send + 'a>>` by hand | boxed | yes | one allocation per call, every caller | | `#[async_trait]` from the async-trait crate | boxed | yes | the same; the macro writes the signature | | Native trait plus an erased companion trait with a blanket impl | not boxed | yes, through the companion | allocation only on the dyn path; a second trait | | An enum over the known backends, matching in each method | n/a | no trait object needed | closed set; every new backend edits the enum | 1. **Box the future in the signature.** `fn get<'a>(&'a self, key: &'a str) -> Pin<Box<dyn Future<Output = Option<Vec<u8>>> + Send + 'a>>` has one concrete return type, so it is dispatchable. Implementors write `Box::pin(async move { ... })`. 2. **Erase only where needed.** Keep `Storage` native (ideally with a `+ Send` future) for generic code, and define `DynStorage` with the boxed signature plus `impl<T: Storage> DynStorage for T`. Generic callers pay nothing; `Box<dyn DynStorage>` users pay one box per call. 3. **Enum dispatch.** When the backends are fixed and known, `enum Backend { Memory(RamStore), Remote(RemoteStore) }` with an `async fn get` that matches avoids both the vtable and the box. ## A tempting non-fix Adding `where Self: Sized` to `get` makes it **explicitly non-dispatchable**: the trait becomes dyn-compatible again, but `get` cannot be called through `dyn Storage`. That helps only when the async method is an extra the dyn users do not need. Likewise `trait_variant::make` does not help, because the trait it generates still returns `impl Future`. Native `dyn` support for async methods is still unstable in 1.99. ## How the erased companion works The companion pattern in the second example has three parts: 1. `Storage` is the trait implementors write, with `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> + Send`, so an implementor writes a plain `async fn get`. 2. `DynStorage` repeats each method with an explicit lifetime `'a` tying `&self` and `key` to the boxed future, so the future may borrow both. 3. `impl<T: Storage> DynStorage for T` calls `Storage::get(self, key)` and wraps the result in `Box::pin`. The fully qualified call states the intent; it also matters to users, because a concrete `RamStore` now has two `get` methods, and `RamStore.get(k)` with both traits in scope fails with E0034 (multiple applicable items) until the caller writes `Storage::get(&store, k)` or imports only one trait. No implementor ever writes `DynStorage` by hand, so adding a backend costs nothing extra, and code that holds `Box<dyn DynStorage>` pays one allocation per call while generic code pays none. ## How to choose - Mostly generic callers and one dyn site: the erased companion trait. - Dyn everywhere, allocation cost irrelevant: the async-trait crate. - A small closed set of backends: an enum.
- Why does a method returning `Pin<Box<dyn Future<Output = T> + Send + 'a>>` pass the dyn-compatibility check?Its return type is one concrete type, a pinned box holding a trait object, for every implementor. The vtable entry can therefore have a single signature, and the box hides each impl's real future behind dynamic dispatch of `poll`. The price is a heap allocation per call.
- When is enum dispatch a better fix than boxing?When the set of backends is closed and owned by one crate. An enum with one variant per backend implements the async method by matching and awaiting the inner store, so there is no vtable and no allocation. It stops working once third parties must add backends, because each one would have to edit the enum.
- The &self receiver is what makes the async method undispatchable.
- Adding where Self: Sized lets dyn Storage call get with a boxed future.
- trait_variant::make produces a variant usable as Box<dyn Trait>.
- Lifetime parameters on async methods are what break the vtable.
- Boxing is unavoidable for generic callers once any dyn user exists.