patternrustModerate
Rust async traits not supported directly — use async-trait crate
Viewed 0 times
Rust 1.75+ for native, async-trait crate for older
async traitasync-trait cratePin Box Futuredynamic dispatchobject safety
Problem
Defining async methods in traits fails with errors about impl Future not being object-safe. Cannot use async fn in trait definitions.
Solution
As of Rust 1.75+, async fn in traits is stable for static dispatch. For dynamic dispatch (dyn Trait), use the async-trait crate: #[async_trait] on both trait definition and impl. Alternative: return Pin<Box<dyn Future>> manually. For new code on Rust 1.75+, prefer native async traits with impl Trait return types. The async-trait crate adds heap allocation overhead due to boxing.
Why
Async functions return opaque Future types whose size varies per implementation. Trait objects need known sizes, so async in traits requires boxing or static dispatch.
Revisions (0)
No revisions yet.