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_back2
        if let Some(call_back2_type) = &self.call_back2 {
   
            call_back2_type();
            call_back2_type();
        } else {
   
            println!("No callback2 to execute.");
        }

        //call_back3
        if let Some(call_back3_type) = &self.call_back3 {
   
            let result = call_back3_type();
        } else {
   
            println!("No callback3 to execute.");
        }

        //call_back4
        if 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_back5
        self.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();
}

相关推荐

  1. Rust CallBack写法

    2024-02-18 18:54:05       30 阅读
  2. vue3:中warch监听写法

    2024-02-18 18:54:05       36 阅读
  3. Linux Shell,遍历数组或文件不同写法

    2024-02-18 18:54:05       13 阅读
  4. hive将时间字符串转换为timestamp写法

    2024-02-18 18:54:05       15 阅读
  5. 单例模式写法

    2024-02-18 18:54:05       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-18 18:54:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-18 18:54:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-18 18:54:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-18 18:54:05       20 阅读

热门阅读

  1. 11-编写自动化测试

    2024-02-18 18:54:05       30 阅读
  2. 12-输入/输出项目构建命令行程序

    2024-02-18 18:54:05       29 阅读
  3. [蓝桥2022国赛] 费用报销

    2024-02-18 18:54:05       27 阅读
  4. 贪吃蛇小游戏

    2024-02-18 18:54:05       27 阅读
  5. PCIE 4.0 Power Mangement

    2024-02-18 18:54:05       26 阅读
  6. python用socket传输图片

    2024-02-18 18:54:05       27 阅读
  7. Redis常用命令

    2024-02-18 18:54:05       27 阅读
  8. 4 存储器管理(下)

    2024-02-18 18:54:05       26 阅读
  9. 16.3 Spring框架_SpringJDBC与事务管理(❤❤❤❤)

    2024-02-18 18:54:05       28 阅读
  10. Docker-compose容器编排技术

    2024-02-18 18:54:05       25 阅读
  11. CSS的伪类选择器:nth-child()的用法示例

    2024-02-18 18:54:05       34 阅读
  12. Android13.0 系统Framework发送通知流程分析

    2024-02-18 18:54:05       31 阅读
  13. stable diffusion webui学习总结(3):参数设置

    2024-02-18 18:54:05       30 阅读