In Rust 1.75 and later, when is the async-trait crate's `#[async_trait]` still needed, and what does it cost per call?
answer
- dyn dispatch, or an old MSRV
- a pinned box per call
- Send unless told otherwise
- annotate trait and impl
basics
~20 sSince 1.75, async-trait is needed mainly for dyn Trait use of async methods, or code supporting older compilers. Each call returns Pin<Box<dyn Future + Send>>: one heap allocation and dynamic poll dispatch, with Send required unless ?Send is used.
solid answer
~40 sNative `async fn` in traits arrived in Rust 1.75, so purely generic use no longer needs the crate. `#[async_trait]` is still the simple answer when you need `Box<dyn Storage>` or `&dyn Storage` with async methods, which native async fn cannot do, or when a crate must build on compilers older than 1.75. The macro rewrites each `async fn` to return `Pin<Box<dyn Future<Output = T> + Send + 'async_trait>>` and wraps the body in `Box::pin(async move { ... })`, so every call allocates once and polls through a vtable, generic callers included. The future must be `Send` by default; `#[async_trait(?Send)]` drops that. Both the trait and every impl need the attribute, or the signatures do not match and rustc reports E0195.
code
rust · 32 linesuse async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Mutex;
#[async_trait]
trait Storage {
async fn get(&self, key: &str) -> Option<Vec<u8>>;
async fn put(&self, key: &str, value: Vec<u8>);
}
struct RamStore(Mutex<HashMap<String, Vec<u8>>>);
#[async_trait]
impl Storage for RamStore {
async fn get(&self, key: &str) -> Option<Vec<u8>> {
self.0.lock().unwrap().get(key).cloned()
}
async fn put(&self, key: &str, value: Vec<u8>) {
self.0.lock().unwrap().insert(key.to_owned(), value);
}
}
fn main() {
let stores: Vec<Box<dyn Storage + Send + Sync>> =
vec![Box::new(RamStore(Mutex::new(HashMap::new())))];
futures::executor::block_on(async {
for s in &stores {
s.put("k", vec![1, 2]).await;
println!("{:?}", s.get("k").await);
}
});
}go deeper
Know that async-trait was the pre-1.75 way to write async methods in traits and that it is still used for dyn Trait.
Describe the expansion to Pin<Box<dyn Future + Send>>, the per-call allocation, the ?Send option and the attribute on both trait and impl.
Judge when the allocation matters, diagnose E0195 from a missing attribute, and prefer + Send desugaring when only the Send guarantee is wanted.
Treat the choice as public API: switching between async-trait and native async fn later breaks downstream implementors and dyn users.
## What the crate is for now Before Rust 1.75 a trait could not declare `async fn` on stable, and the async-trait crate was the standard workaround. Since 1.75 native `async fn` in traits covers generic use, which removes the crate's original reason to exist. It still earns its place in two situations: - **Dynamic dispatch.** Native async methods make a trait dyn-incompatible (E0038). With `#[async_trait]`, `Vec<Box<dyn Storage + Send + Sync>>` or `&dyn Storage` just work, which is why the crate's own README now leads with this case. - **Old compilers.** A library whose minimum supported Rust version is below 1.75 cannot use native async fn in traits. A third, weaker reason: the default expansion also guarantees `Send` futures, which native async fn does not. On 1.99 that alone is better solved without allocation, with `-> impl Future + Send` in the trait or `trait_variant`. ## What the macro generates For `async fn get(&self, key: &str) -> Option<Vec<u8>>` the attribute produces, in outline: ```rust fn get<'life0, 'life1, 'async_trait>(&'life0 self, key: &'life1 str) -> Pin<Box<dyn Future<Output = Option<Vec<u8>>> + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait { Box::pin(async move { /* the original body */ }) } ``` The exact lifetimes and where clauses are the macro's business; what matters is the shape: 1. The return type is **one concrete type**, a pinned box of a trait object, so the method is dispatchable and the trait is dyn-compatible. 2. The box is `Pin<Box<...>>` because `Box<dyn Future>` alone is not a future: std implements `Future` for `Box<F>` only when `F: Unpin`, and an async block is not. 3. The default trait object is `dyn Future + Send`, so an implementation that holds an `Rc` or a std `MutexGuard` across an `.await` fails with "future cannot be sent between threads safely". ## What it costs | Cost | Native async fn (generic call) | `#[async_trait]` | |---|---|---| | Heap allocation | none | one `Box` per call | | Polling | static, inlinable | through the trait object's vtable | | `Send` | not promised | required unless `?Send` | | `dyn Trait` | not possible | possible | The Async Book's note on the crate puts the trade-off plainly: one heap allocation per call is not significant for most applications, but it matters for a low-level API called millions of times a second. Note that the cost applies to **every** call, generic ones included, because the macro changes the trait's own signature. ## Rules for using it - Put `#[async_trait]` on the trait **and** on every impl. An impl without it writes a plain `async fn` against a boxed signature and rustc reports E0195 ("lifetime parameters or bounds on method `get` do not match the trait declaration"); the same error appears the other way round. - Use `#[async_trait(?Send)]` on both, for single-threaded executors or `!Send` state. - Add `Send + Sync` to the trait object type (`Box<dyn Storage + Send + Sync>`) when the object itself crosses threads; the macro bounds the futures, not the object. - A lifetime elided in a path type, such as a `Parser<'a>` argument written `Parser`, must be written `Parser<'_>`; rustc reports E0726 otherwise, as it does for any async fn. ## Deciding whether to keep it in an existing crate A useful audit for a codebase that adopted async-trait before 1.75: 1. List the traits carrying `#[async_trait]` and check whether any is used as `dyn Trait`. 2. A trait never used as a trait object can move to native `async fn`, written as `fn ... -> impl Future<Output = T> + Send` if its futures are spawned; the allocation disappears and nothing else changes for callers inside the crate. 3. A trait used as a trait object keeps the attribute, or moves to a native trait plus an erased companion if profiling shows the allocation matters. 4. A public trait is a SemVer question: changing it is a breaking change, so batch it with other major-version work. Where dyn use is the need but generic hot paths must stay unboxed, an erased companion trait with a blanket impl is the alternative; that design choice is the subject of a separate question.
- What does `#[async_trait(?Send)]` change, and where must it go?It drops the `Send` bound from the boxed future, so the generated return type is `Pin<Box<dyn Future<Output = T> + 'async_trait>>` and implementations may hold `!Send` values such as `Rc` across `.await`. It must appear on the trait and on every impl, because the two signatures have to match.
- Is moving a published trait from `#[async_trait]` to native `async fn` a compatible change?No. The method's return type changes from a pinned boxed future to an opaque one, `dyn Storage` stops compiling for downstream users, and impls still annotated with `#[async_trait]` no longer match the trait (E0195). Under Cargo's SemVer rules that needs a new major version.
- Native async fn in traits made the async-trait crate obsolete in every case.
- async-trait boxes only dyn calls, so generic callers pay nothing.
- The macro is needed only on the trait, not on the impls.
- async-trait futures are not Send unless you opt in.
- Box<dyn Future> without Pin would work just as well.
Assumes Rust 1.75 or later (checked on 1.99) with async-trait 0.1.92; before 1.75 the crate was the only stable way to write async methods in traits.