1#[macro_use(defer)]
2extern crate scopeguard;
3
4use scopeguard::guard;
5
6fn f() {
7 defer! {
8 println!("Called at return or panic");
9 }
10 panic!();
11}
12
13use std::fs::File;
14use std::io::Write;
15
16fn 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
26fn main() {
27 f();
28 g();
29}
30