dtolnay/async-trait hiện có 2.2k sao trên GitHub, viết chủ yếu bằng Rust. Type erasure for async trait methods
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
VÌ SAO CHƯA CÓ REVIEW
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
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:
error[E0038]: the trait `Trait` is not dyn compatible
--> src/main.rs:5:22
|
5 | pub fn make() -> Box<dyn Trait> {
| ^^^^^^^^^ `Trait` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> src/main.rs:2:14
|
1 | pub trait Trait {
| ----- this trait is not dyn compatible...
2 | async fn f(&self);
| ^ ...because method `f` is `async`
= help: consider moving `f` to another trait
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 for a deeper analysis
of how this implementation differs from what the compiler and language deliver
natively.
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<Box<dyn Advertisement + Sync>> or &[&dyn Advertisement], for
example.
use async_trait::async_trait;
#[async_trait]
trait Advertisement {
async fn run(&self);
}
struct Modal;
#[async_trait]
impl Advertisement for Modal {
async fn run(&self) {
self.render_fullscreen().await;
for _ in 0..4u16 {
remind_user_to_join_mailing_list().await;
}
self.hide_for_now().await;
}
}
struct AutoplayingVideo {
media_url: String,
}
#[async_trait]
impl Advertisement for AutoplayingVideo {
async fn run(&self) {
let stream = connect(&self.media_url).await;
stream.play().await;
// Video probably persuaded user to join our mailing list!
Modal.run().await;
}
}
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<Box<dyn Future + Send + 'async_trait>> and delegate to an async block.
For example the impl Advertisement for AutoplayingVideo above would be
expanded as:
impl Advertisement for AutoplayingVideo {
fn run<'async_trait>(
&'async_trait self,
) -> Pin<Box<dyn std::future::Future<Output = ()> + 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.
type Elided<'a> = &'a usize;
#[async_trait]
trait Test {
async fn test(not_okay: Elided, okay: &usize) {}
}
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 '_.
#[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.
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/dtolnay/async-trait là nguồn chính thức.
dtolnay/async-trait có bao nhiêu sao?
dtolnay/async-trait có 2.2k sao GitHub — tải lại trang để xem số mới nhất, hoặc xem trực tiếp github.com/dtolnay/async-trait. TopGit phản chiếu số sao của GitHub nhưng không cam kết đến từng phút.
dtolnay/async-trait có phải mã nguồn mở không?
Có — dtolnay/async-trait phát hành theo license Apache-2.0, nghĩa là mã nguồn mở để đọc, fork và (tùy license) tái sử dụng. Mã: github.com/dtolnay/async-trait.
dtolnay/async-trait còn đang phát triển không?
Commit gần nhất trên dtolnay/async-trait là 5 ngày trước (theo timestamp GitHub). Repo có 103 fork — một chỉ báo về mức độ quan tâm của cộng đồng.
dtolnay/async-trait dùng license gì?
dtolnay/async-trait phát hành theo license Apache-2.0. Nên mở file LICENSE trên GitHub để xác nhận — license metadata đôi khi lệch với thực tế dự án.
dtolnay/async-trait là gì?
dtolnay/async-trait (dtolnay/async-trait) là dự án Rust trên GitHub. Theo mô tả gốc: Type erasure for async trait methods
dtolnay/async-trait viết bằng ngôn ngữ gì?
dtolnay/async-trait chủ yếu viết bằng Rust. Trường "language" của GitHub dựa trên phần lớn byte ở nhánh mặc định.
Đọc đầy đủ README ở tab phía trên.
async-trait có đáng để bạn bỏ thời gian?
ChatGPT, Claude và Perplexity đều đọc được trang này. Hỏi thử xem họ nghĩ gì về async-trait.