| 1 |
#[macro_use(defer)] |
| 2 |
extern crate scopeguard; |
| 3 |
|
| 4 |
use scopeguard::guard; |
| 5 |
|
| 6 |
fn f() { |
| 7 |
defer! { |
| 8 |
println!("Called at return or panic"); |
| 9 |
} |
| 10 |
panic!(); |
| 11 |
} |
| 12 |
|
| 13 |
use std::fs::File; |
| 14 |
use std::io::Write; |
| 15 |
|
| 16 |
fn g() { |
| 17 |
let f = File::create("newfile.txt").unwrap(); |
| 18 |
let mut file = guard(f, |f| { |
| 19 |
// write file at return or panic |
| 20 |
let _ = f.sync_all(); |
| 21 |
}); |
| 22 |
// access the file through the scope guard itself |
| 23 |
file.write_all(b"test me\n").unwrap(); |
| 24 |
} |
| 25 |
|
| 26 |
fn main() { |
| 27 |
f(); |
| 28 |
g(); |
| 29 |
} |