diff --git a/examples/defer.rs b/examples/defer.rs new file mode 100644 index 000000000..eadac795f --- /dev/null +++ b/examples/defer.rs @@ -0,0 +1,31 @@ +// Go's defer in Rust! + +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 } +} + +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