< 返回版块

eric642 发表于 2025-07-05 16:31

pub trait UserCommunication {
    async fn send_sms(self: &Self, phone: &str, code: &str);
    async fn send_email(self: &Self, email: &str, code: &str);
}

pub struct AuthenticationService {
    communicator: Box<dyn UserCommunication>,
}

如上代码,希望communicator是个动态分发的trait,不咋想用async-trait实现

评论区

写评论
ztNozdormu 2025-07-14 09:33
  1. 定义trait #[async_trait::async_trait] pub trait UserCommunication: Send + Sync { async fn send_sms(&self, phone: &str, code: &str) { println!("Default SMS not supported."); }

    async fn send_email(&self, email: &str, code: &str) { println!("Default Email not supported."); } }

  2. 定义实现类 #[derive(Clone)] pub struct SmsCommunicator;

#[async_trait::async_trait] impl UserCommunication for SmsCommunicator { async fn send_sms(&self, phone: &str, code: &str) { println!("✅ SMS: {} => {}", phone, code); } }

#[derive(Clone)] pub struct EmailCommunicator;

#[async_trait::async_trait] impl UserCommunication for EmailCommunicator { async fn send_email(&self, email: &str, code: &str) { println!("✅ Email: {} => {}", email, code); } } 3. 定义 AuthenticationService pub struct AuthenticationService<C: UserCommunication> { communicator: C, }

impl<C: UserCommunication> AuthenticationService { pub fn new(communicator: C) -> Self { Self { communicator } }

pub async fn auth_sms(&self, phone: &str, code: &str) {
    self.communicator.send_sms(phone, code).await;
}

pub async fn auth_email(&self, email: &str, code: &str) {
    self.communicator.send_email(email, code).await;
}

} 4. 使用示例 #[tokio::main] async fn main() { let sms_service = AuthenticationService::new(SmsCommunicator); sms_service.auth_sms("13800138000", "888888").await;

let email_service = AuthenticationService::new(EmailCommunicator);
email_service.auth_email("me@example.com", "123456").await;

}

总结建议:以上为AI生成的使用案例,如果重复性逻辑比较多还可以通过宏进一步简化代码;个人建议既然选择用rust能不用动态分发就不用动态分发;使用其他方式实现同样功能。如果要做业务比较繁杂的项目建议用其他语言。从实现过程也能看出来如果用rust写具体业务(尤其是用户需求多变而且繁杂的项目)就是导弹打蚊子;另外除非你项目拆分的非常细rust写微服务(每个服务职责非常清楚业务单纯化--对外提供服务)也是一种思路。

koushiro 2025-07-13 01:42

不用 async trait, 方法直接返回 BoxFuture 类型 或者直接使用 async-trait crate

苦瓜小仔 2025-07-06 00:12

我今天发的 Rust 日报有介绍 dynify

你的示例已经作为了它的一个 example

其他方式见我总结的 dyn-afit

1 共 3 条评论, 1 页