Skip to content

Instantly share code, notes, and snippets.

@karablin
Last active January 2, 2021 02:10
Show Gist options
  • Save karablin/8568808 to your computer and use it in GitHub Desktop.
Save karablin/8568808 to your computer and use it in GitHub Desktop.
go-like defer for rust
#[feature(macro_rules)];
struct ScopeCall<'cls> {
c: 'cls ||
}
#[unsafe_destructor]
impl<'cls> Drop for ScopeCall<'cls> {
fn drop(&mut self) {
(self.c)();
}
}
macro_rules! defer(
($e:expr) => (
let _scope_call = ScopeCall{ c: || -> () { $e; } };
)
)
fn main() {
let x = ~42u8;
defer!(println!("defer 1"));
defer!({println!("defer 2"); println!("{}", *x)});
println!("normal execution {}", *x);
}
$ ./t.exe
normal execution 42
defer 2
42
defer 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment