about summary refs log tree commit diff
path: root/fun/defer_rs/examples/defer.rs
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@google.com>2019-12-21T00·53+0000
committerVincent Ambo <tazjin@google.com>2019-12-21T00·53+0000
commitfbdc9b1d6009c7b9294542c6935a760a6d5eb819 (patch)
tree64f0a832f2d98f6703f9d7e66be8dc4e2efdf7ae /fun/defer_rs/examples/defer.rs
parentacdd21f8f4b476d280e6b78dca4023b7aabb4999 (diff)
parent426780060dee0abb47c85f839943d35a70b0af01 (diff)
merge(defer.rs): Integrate at //fun/defer_rs r/262
Diffstat (limited to 'fun/defer_rs/examples/defer.rs')
-rw-r--r--fun/defer_rs/examples/defer.rs31
1 files changed, 31 insertions, 0 deletions
diff --git a/fun/defer_rs/examples/defer.rs b/fun/defer_rs/examples/defer.rs
new file mode 100644
index 000000000000..eadac795f8bc
--- /dev/null
+++ b/fun/defer_rs/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