当前位置: 首页 > news >正文

Rust CallBack的几种写法

模拟常用的几种函数调用CallBack的写法。测试调用都放在函数t6_call_back_task中。我正在学习Rust,有不对或者欠缺的地方,欢迎交流指正

type Callback = std::sync::Arc<dyn Fn() + Send + Sync>;
type CallbackReturnVal = std::sync::Arc<dyn Fn() -> Result<String, i32> + Send + Sync>;
type CallbackResult = std::sync::Arc<dyn Fn(Result<String, i32>) + Send + Sync>;pub(crate) trait EventListener {fn on_action1(&self, code: i32);fn on_action2(&self, val: String, code: i32);
}pub(crate) struct Executor {call_back: fn(),call_back2: core::option::Option<Callback>,call_back3: core::option::Option<CallbackReturnVal>,call_back4: core::option::Option<CallbackResult>,listener: Box<dyn EventListener + 'static>,
}struct DefaultEventListener;impl EventListener for DefaultEventListener {fn on_action1(&self, code: i32) {}fn on_action2(&self, val: String, code: i32) {}
}impl Executor {pub fn new() -> Self {let default_callback: fn() = || {println!("Default callback executed");};Executor {call_back: default_callback,call_back2: None,call_back3: None,call_back4: None,listener: Box::new(DefaultEventListener {}),}}pub fn set_call_back(&mut self, cb: fn()) {self.call_back = cb;}pub fn set_call_back2<CB>(&mut self, call_back: CB)where CB: Fn() + Send + Sync + 'static {self.call_back2 = Some(std::sync::Arc::new(call_back));}pub fn set_call_back3<CB>(&mut self, call_back: CB)where CB: Fn() -> Result<String, i32> + Send + Sync + 'static {self.call_back3 = Some(std::sync::Arc::new(call_back));}pub fn set_call_back4<CB>(&mut self, call_back: CB)where CB: Fn(Result<String, i32>) + Send + Sync + 'static {self.call_back4 = Some(std::sync::Arc::new(call_back));}pub fn set_call_back5(&mut self, listener: Box<dyn EventListener + 'static>) {self.listener = listener;}pub fn process_events(&self) {(self.call_back)();//call_back2if let Some(call_back2_type) = &self.call_back2 {call_back2_type();call_back2_type();} else {println!("No callback2 to execute.");}//call_back3if let Some(call_back3_type) = &self.call_back3 {let result = call_back3_type();} else {println!("No callback3 to execute.");}//call_back4if let Some(call_back4_type) = &self.call_back4 {let ok: Result<String, i32> = Result::Ok("success".to_string());let error_code: Result<String, i32> = Result::Err(-10);call_back4_type(ok);} else {println!("No callback4 to execute.");}//call_back5self.listener.on_action1(1);self.listener.on_action2("".to_string(), -1);}
}pub(crate) struct EventListenerImpl {}impl EventListener for EventListenerImpl {fn on_action1(&self, code: i32) {println!("-------on_action1--------code: {}", code);}fn on_action2(&self, val: String, code: i32) {println!("-------on_action2--------code: {} , val: {}", code, val);}
}pub(crate) fn t6_call_back_task() {let mut executor = Executor::new();executor.set_call_back(|| {println!("-------call_back----1----");});executor.set_call_back2(|| {println!("-------call_back----2----");});executor.set_call_back3(|| {println!("-------call_back----3---");Ok("Callback executed successfully!".to_string())});executor.set_call_back4(|result: Result<String, i32>| {println!("-------call_back----4----result: {:?}", result);});let event_listener = Box::new(EventListenerImpl {});executor.set_call_back5(event_listener);executor.process_events();
}
http://www.lryc.cn/news/304063.html

相关文章:

  • Redis突现拒绝连接问题处理总结
  • css中选择器的优先级
  • python3字符串内建方法split()心得
  • html的列表标签
  • 【Pytorch深度学习开发实践学习】B站刘二大人课程笔记整理lecture04反向传播
  • PyTorch使用Tricks:学习率衰减 !!
  • 10MARL深度强化学习 Value Decomposition in Common-Reward Games
  • 2 Nacos适配达梦数据库实现方案
  • 【Gitea】配置 Push To Create
  • 关于postgresql数据库单独设置某个用户日志级别(日志审计)
  • 阿里云ECS香港服务器性能强大、cn2高速网络租用价格表
  • 实战打靶集锦-025-HackInOS
  • list.stream().forEach()和list.forEach()的区别
  • JS基础之JSON对象
  • 嵌入式学习之Linux入门篇——使用VMware创建Unbuntu虚拟机
  • 大模型中的token是什么?
  • 跳表是一种什么样的数据结构
  • 【刷题记录】最大公因数,最小公倍数(辗转相除法、欧几里得算法)
  • ETL快速拉取物流信息
  • 17.1 SpringMVC框架_SpringMVC入门与数据绑定(❤❤)
  • Leetcode 11.盛水最多的容器
  • 《Go 简易速速上手小册》第7章:包管理与模块(2024 最新版)
  • 【论文精读】IBOT
  • Yolo V5在实时视频流中的建筑物与彩钢房检测:性能评估与改进方法
  • 图——最小生成树实现(Kruskal算法,prime算法)
  • Unity3D xLua开发环境搭建详解
  • Python笔记-super().init(root)的作用
  • 【git 使用】使用 git rebase -i 修改任意的提交信息/合并多个提交
  • 【Vue3】toRefs和toRef在reactive中的一些应用
  • 力扣精选算法100道——Z字形变换(模拟专题)