about summary refs log tree commit diff
path: root/examples
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@gmail.com>2017-10-22T15·22+0200
committerVincent Ambo <tazjin@gmail.com>2017-10-22T15·22+0200
commit5eec09334bd17ebb28a57021b56a6e687f433528 (patch)
tree5afba55f6a920c6b80af5ef8d44336d44e7c2595 /examples
parentaabac498e76339d7c47a0bf39dbb883b3a3e4407 (diff)
feat: Add Drop-based defer implementation
Diffstat (limited to 'examples')
-rw-r--r--examples/defer.rs31
1 files changed, 31 insertions, 0 deletions
diff --git a/examples/defer.rs b/examples/defer.rs
new file mode 100644
index 000000000000..eadac795f8bc
--- /dev/null
+++ b/examples/defer.rs
@@ -0,0 +1,31 @@
+// Go's defer in Rust!
+
+struct Defer<F: Fn()> {
+    f: F
+}
+
+impl <F: Fn()> Drop for Defer<F> {
+    fn drop(&mut self) {
+        (self.f)()
+    }
+}
+
+// Only added this for Go-syntax familiarity ;-)
+fn  defer<F: Fn()>(f: F) -> Defer<F> {
+    Defer { f }
+}
+
+fn main() {
+    let mut i = 1;
+
+    // Calling it "token" ... could be something else. The lifetime of this
+    // controls when the action is run.
+    let _token = defer(move || println!("Value is: {}", i));
+
+    i += 1;
+    println!("Value is: {}", i);
+}
+
+// Prints:
+// Value is: 2
+// Value is: 1