6 个版本 (3 个重大变更)
| 0.7.0 | 2022 年 6 月 18 日 |
|---|---|
| 0.6.1 | 2022 年 6 月 18 日 |
| 0.6.0 | 2022 年 1 月 29 日 |
| 0.2.1 | 2021 年 11 月 11 日 |
| 0.1.0 | 2021 年 11 月 9 日 |
#2551 在 Rust 模式
在 alhc 中使用
6KB
60 行
async_t
放弃动态分派,获得编译时异步特质(附带一些额外功能)
async_t 提供了一个 #[impl_trait] 宏,允许任何特质返回存在类型;例如 -> impl Future 和一个 #[async_trait] 宏,该宏将您的异步方法包装在 -> impl Future 存在类型下。
这允许完全零成本的异步特质,并允许递归存在返回类型,例如 Result<impl Display, impl Debug>。
它可能在需要指定生命周期的位置存在问题。
// spawn example
#[async_trait]
trait Spawn {
// supports self, &self, &mut self and no self
async fn spawn() -> JoinHandle<()>;
}
#[async_trait]
impl Spawn for Spawner {
async fn spawn() -> JoinHandle<()> {
task::sleep(Duration::from_secs(2)).await; // await inside
task::spawn(async {
// ...
})
}
}
async fn spawn<T: Spawn>() -> JoinHandle<()> {
T::spawn().await
}
#[async_trait]
trait Sleeper {
#[unsend]
async fn sleep<T>(t: T) -> T;
}
#[async_trait]
impl Sleeper for () {
#[unsend]
async fn sleep<T>(t: T) -> T {
task::sleep(Duration::from_secs(2)).await;
t
}
}
async_t 还支持特质中的 impl 返回类型(异步特质旨在设计递归 impl 返回类型)
#[impl_trait] // #[async_trait] can also be used
trait RetDebug {
fn ret_debug() -> impl Debug;
}
功能
async_t 支持 boxed 功能,这将 async_trait 设置为来自 dtolnay 的 async-trait crate 的一个。
依赖项
~1.5MB
~36K SLoC