hook_test.rs 921 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // 主方法模拟
  2. struct Main {
  3. spread_list: Vec<f64>,
  4. }
  5. impl Main {
  6. fn new() -> Main {
  7. Main {
  8. spread_list: Vec::new(),
  9. }
  10. }
  11. // 钩子演示方法
  12. fn hook_func_demo(&mut self, depth_spread: &f64) {
  13. self.spread_list.push(depth_spread.clone());
  14. }
  15. }
  16. // 中间键模拟
  17. struct MiddleWare {
  18. deep_spread: f64,
  19. }
  20. impl MiddleWare {
  21. fn new(spread: f64) -> MiddleWare {
  22. MiddleWare {
  23. deep_spread: spread,
  24. }
  25. }
  26. fn call_hook<F: FnMut(&f64)>(&self, mut hook: F) {
  27. // 中间键去将钩子再传给接口
  28. hook(&self.deep_spread);
  29. }
  30. }
  31. // 主逻辑->中间键的钩子使用演示
  32. #[tokio::test]
  33. async fn test_hook() {
  34. let mut a = Main::new();
  35. let b = MiddleWare::new(0.1);
  36. let hook = |deep_spread: &f64| a.hook_func_demo(deep_spread);
  37. b.call_hook(hook);
  38. println!("{:?}", a.spread_list);
  39. }