diff options
author | Vincent Ambo <tazjin@gmail.com> | 2017-10-22T15·35+0200 |
---|---|---|
committer | Vincent Ambo <tazjin@gmail.com> | 2017-10-22T15·35+0200 |
commit | 49a553c5c58c9e32ce1d1f15e37cb6ddd16afab6 (patch) | |
tree | 98866ca0fe47fd6a8e480bff8bbceb26bbcc5e70 /examples/undefer.rs | |
parent | ff7b5b42bf3d761cbf28e56f30796059ef94e271 (diff) |
feat: Add spooky undefer implementation
Diffstat (limited to 'examples/undefer.rs')
-rw-r--r-- | examples/undefer.rs | 40 |
1 files changed, 40 insertions, 0 deletions
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: 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 } +} + +// Changed your mind about the defer? +// (Note: This leaks the closure! Don't actually do this!) +fn undefer<F: Fn()>(token: Defer<F>) { + 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 |