Debian Codegraph @

third_party/rust/scopeguard/examples/readme.rs

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