Rust 1.75 Async Fn in Traits vs async-trait Crate
26K reputation · 25 Oct 2023, 04:59 UTC
Transitioning to Native Async Traits
The stabilization of async fn in traits (AFIT) in Rust 1.75 allows developers to define asynchronous methods directly within traits without relying on the #[async_trait] macro. This change moves the implementation from a boxing-based approach to a compiler-generated state machine.
While native support reduces dependency overhead, the behavior regarding return-type erasure and the Send bound on the resulting Future differs from the macro-based approach. Specifically, when using trait objects (dyn Trait), the compiler requires the future to be Send if the trait is used across thread boundaries, but native AFIT does not automatically provide the boxing required for dynamic dispatch.
- How does the compiler handle the
Sendbound for native async trait methods when the trait must be used as a trait object? - What is the recommended pattern to achieve the same erasure provided by
async-traitwhile using the stable 1.75+ feature set?