跳过正文

async-trait

Rust Rust-Crate
目录
rust crate - 这篇文章属于一个选集。
§ 6: 本文

async-trait
#

目前,Rust trait 中如果包含 async 函数,则不允许使用 trait object:

pub trait Trait {
    async fn f(&self);
}
pub fn make() -> Box<dyn Trait> {
    unimplemented!()
}

// 报错
error[E0038]: the trait `Trait` cannot be made into an object
 --> src/main.rs:5:22
  |
5 | pub fn make() -> Box<dyn Trait> {
  |                      ^^^^^^^^^ `Trait` cannot be made into an object
  |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
 --> src/main.rs:2:14
  |
1 | pub trait Trait {
  |           ----- this trait cannot be made into an object...
2 |     async fn f(&self);
  |              ^ ...because method `f` is `async`
  = help: consider moving `f` to another trait

async-trait 则提供了 attribute macro 的解决方案:在定义和实现包含 async 函数或方法的 trait 时,添加 #[async_trait] 属性宏:

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;
    }
}
rust crate - 这篇文章属于一个选集。
§ 6: 本文

相关文章

sqlx
·
Rust Rust-Crate
sqlx 是异步的 SQL mapper。
axum
·
Rust Rust-Crate
axum 是基于 hyper 实现的高性能异步 HTTP 1/2 Server 库。
clap
·
Rust Rust-Crate
clap 用于快速构建命令行程序,提供命令&参数定义、解析等功能。
config
·
Rust Rust-Crate
config 提供从文件或环境变量解析配置参数的功能。