about summary refs log tree commit diff
path: root/fun/defer_rs/examples/defer.rs
blob: 0c99d00c82dfe87183e60174c20546ad319730e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Go's defer in Rust!

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 }
}

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