فهرست منبع

hook的例子

skyfffire 2 سال پیش
والد
کامیت
72c91be7c7
1فایلهای تغییر یافته به همراه45 افزوده شده و 0 حذف شده
  1. 45 0
      tests/hoot_test.rs

+ 45 - 0
tests/hoot_test.rs

@@ -0,0 +1,45 @@
+// 主方法模拟
+struct Main {
+    spread_list: Vec<f64>,
+}
+impl Main {
+    fn new() -> Main {
+        Main {
+            spread_list: Vec::new(),
+        }
+    }
+
+    // 钩子演示方法
+    fn hook_func_demo(&mut self, depth_spread: &f64) {
+        self.spread_list.push(depth_spread.clone());
+    }
+}
+
+// 中间键模拟
+struct MiddleWare {
+    deep_spread: f64,
+}
+impl MiddleWare {
+    fn new(spread: f64) -> MiddleWare {
+        MiddleWare {
+            deep_spread: spread,
+        }
+    }
+
+    fn call_hook<F: FnMut(&f64)>(&self, mut hook: F) {
+        // 中间键去将钩子再传给接口
+        hook(&self.deep_spread);
+    }
+}
+
+// 主逻辑->中间键的钩子使用演示
+#[tokio::test]
+async fn test_hook() {
+    let mut a = Main::new();
+    let b = MiddleWare::new(0.1);
+
+    let hook = |deep_spread: &f64| a.hook_func_demo(deep_spread);
+    b.call_hook(hook);
+
+    println!("{:?}", a.spread_list);
+}