2017-10-22 17:22:05 +02:00
|
|
|
// Go's defer in Rust!
|
|
|
|
|
|
|
|
struct Defer<F: Fn()> {
|
2022-02-07 16:49:59 +01:00
|
|
|
f: F,
|
2017-10-22 17:22:05 +02:00
|
|
|
}
|
|
|
|
|
2022-02-07 16:49:59 +01:00
|
|
|
impl<F: Fn()> Drop for Defer<F> {
|
2017-10-22 17:22:05 +02:00
|
|
|
fn drop(&mut self) {
|
|
|
|
(self.f)()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only added this for Go-syntax familiarity ;-)
|
2022-02-07 16:49:59 +01:00
|
|
|
fn defer<F: Fn()>(f: F) -> Defer<F> {
|
2017-10-22 17:22:05 +02:00
|
|
|
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
|