Last active
January 2, 2021 02:10
-
-
Save karablin/8568808 to your computer and use it in GitHub Desktop.
go-like defer for rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./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