Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

async-trait

> 编程语言
Open source

Type erasure for async trait methods

2.2K stars0 likes0 views
WebsiteGitHub

About

Type erasure for async trait methods

Async trait methods =================== [](https://github.com/dtolnay/async-trait) [](https://crates.io/crates/async-trait) [](https://docs.rs/async-trait) [](https://github.com/dtolnay/async-trait/actions?query=branch%3Amaster) The stabilization of async functions in traits in Rust 1.75 did not include support for using traits containing async functions as `dyn Trait`. Trying to use dyn with an async trait produces the following error: ```rust pub trait Trait { async fn f(&self); } pub fn make() -> Box { unimplemented!() } ``` ``` … ``` This crate provides an attribute macro to make async fn in traits work with dyn traits. Please refer to [*why async fn in traits are hard*][hard] for a deeper analysis of how this implementation differs from what the compiler and language deliver natively. [hard]: https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/
## Example This example implements the core of a highly effective advertising platform using async fn in a trait. The only thing to notice here is that we write an `#[async_trait]` macro on top of traits and trait impls that contain async fn, and then they work. We get to have `Vec>` or `&[&dyn Advertisement]`, for example. ``` … ```
## Supported features It is the intention that all features of Rust traits should work nicely with \#\[async_trait\], but the edge cases are numerous. *Please file an issue if you see unexpected borrow checker errors, type errors, or warnings.* There is no use of `unsafe` in the expanded code, so rest assured that if your code compiles it can't be that badly broken. - 👍 Self by value, by reference, by mut reference, or no self; - 👍 Any number of arguments, any return value; - 👍 Generic type parameters and lifetime parameters; - 👍 Associated types; - 👍 Having async and non-async functions in the same trait; - 👍 Default implementations provided by the trait; - 👍 Elided lifetimes.
## Explanation Async fns get transformed into methods that return `Pin>` and delegate to an async block. For example the `impl Advertisement for AutoplayingVideo` above would be expanded as: ```rust impl Advertisement for AutoplayingVideo { fn run<'async_trait>( &'async_trait self, ) -> Pin + Send + 'async_trait>> where Self: Sync + 'async_trait, { Box::pin(async move { /* the original method body */ }) } } ```
## Non-threadsafe futures Not all async traits need futures that are `dyn Future + Send`. To avoid having Send and Sync bounds placed on the async trait methods, invoke the async trait macro as `#[async_trait(?Send)]` on both the trait and the impl blocks.
## Elided lifetimes Be aware that async fn syntax does not allow lifetime elision outside of `&` and `&mut` references. (This is true even when not using #\[async_trait\].) Lifetimes must be named or marked by the placeholder `'_`. Fortunately the compiler is able to diagnose missing lifetimes with a good error message. ```rust type Elided<'a> = &'a usize; #[async_trait] trait Test { async fn test(not_okay: Elided, okay: &usize) {} } ``` ```console error[E0726]: implicit elided lifetime not allowed here --> src/main.rs:9:29 | 9 | async fn test(not_okay: Elided, okay: &usize) {} | ^^^^^^- help: indicate the anonymous lifetime: `<'_>` ``` The fix is to name the lifetime or use `'_`. ```rust #[async_trait] trait Test { // either async fn test<'e>(elided: Elided<'e>) {} // or async fn test(elided: Elided<'_>) {} } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

GitHub Issues· 0 open

View all on GitHub

No open issues yet, or sync has not completed.

Highlights

  • •&#128077;&ensp;Self by value, by reference, by mut reference, or no self;
  • •&#128077;&ensp;Any number of arguments, any return value;
  • •&#128077;&ensp;Generic type parameters and lifetime parameters;
  • •&#128077;&ensp;Associated types;
  • •&#128077;&ensp;Having async and non-async functions in the same trait;
  • •&#128077;&ensp;Default implementations provided by the trait;
  • •&#128077;&ensp;Elided lifetimes.

> Tags

Rust

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言