diff options
author | Vincent Ambo <tazjin@google.com> | 2019-12-21T00·53+0000 |
---|---|---|
committer | Vincent Ambo <tazjin@google.com> | 2019-12-21T00·53+0000 |
commit | 426780060dee0abb47c85f839943d35a70b0af01 (patch) | |
tree | 26d49f2b2b571c3ec8094de7da9856d46e850711 /fun/defer_rs/examples/undefer.rs | |
parent | 6193726fb7ba858254eaeec5d790ad7828bd13e9 (diff) |
chore(defer.rs): Prepare for depot merge
Diffstat (limited to 'fun/defer_rs/examples/undefer.rs')
-rw-r--r-- | fun/defer_rs/examples/undefer.rs | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/fun/defer_rs/examples/undefer.rs b/fun/defer_rs/examples/undefer.rs new file mode 100644 index 000000000000..17ad8a6b5485 --- /dev/null +++ b/fun/defer_rs/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 |