From 49a553c5c58c9e32ce1d1f15e37cb6ddd16afab6 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sun, 22 Oct 2017 17:35:45 +0200 Subject: feat: Add spooky undefer implementation --- examples/undefer.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 examples/undefer.rs (limited to 'examples') diff --git a/examples/undefer.rs b/examples/undefer.rs new file mode 100644 index 000000000000..17ad8a6b5485 --- /dev/null +++ b/examples/undefer.rs @@ -0,0 +1,40 @@ +// Go's defer in Rust, with a little twist! + +struct Defer { + f: F +} + +impl Drop for Defer { + fn drop(&mut self) { + (self.f)() + } +} + +// Only added this for Go-syntax familiarity ;-) +fn defer(f: F) -> Defer { + Defer { f } +} + +// Changed your mind about the defer? +// (Note: This leaks the closure! Don't actually do this!) +fn undefer(token: Defer) { + use std::mem; + mem::forget(token); +} + +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); + + // Oh, now I changed my mind about the previous defer: + undefer(token); +} + +// Prints: +// Value is: 2 -- cgit 1.4.1