Last active
July 7, 2019 15:25
-
-
Save xbee/4c5210594ac66818861b16c07aeac919 to your computer and use it in GitHub Desktop.
Golang like defer in Rust #rust #defer
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
// from: https://stackoverflow.com/questions/29963449/golang-like-defer-in-rust | |
// | |
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