Created
July 15, 2015 03:49
-
-
Save thearchitect/4ec1c3ed373de9331b7a to your computer and use it in GitHub Desktop.
Golang like defers 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
// http://stackoverflow.com/a/29963675/983835 | |
struct ScopeCall<F: FnOnce()> { | |
c: Option<F> | |
} | |
impl<F: FnOnce()> Drop for ScopeCall<F> { | |
fn drop(&mut self) { | |
self.c.take().unwrap()() | |
} | |
} | |
macro_rules! expr { ($e: expr) => { $e } } // tt hack | |
macro_rules! defer { | |
($($data: tt)*) => ( | |
let _scope_call = ScopeCall { | |
c: Some(|| -> () { expr!({ $($data)* }) }) | |
}; | |
) | |
} | |
fn main() { | |
let x = 42u8; | |
defer!(println!("defer 1")); | |
defer! { | |
println!("defer 2"); | |
println!("inside defer {}", x) | |
} | |
println!("normal execution {}", x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please put this on crates.io 👍