Skip to content

Instantly share code, notes, and snippets.

@c-cube
Created August 5, 2020 19:15
Show Gist options
  • Save c-cube/51f918457943907722ea7b47f95be229 to your computer and use it in GitHub Desktop.
Save c-cube/51f918457943907722ea7b47f95be229 to your computer and use it in GitHub Desktop.
`defer` in pure rust
struct Defer<F: FnMut() + Sized>(F);
macro_rules! defer {
($($f: expr);+) => { let _d = Defer(|| {$($f);+}); }
}
impl<F:FnMut() + Sized> Drop for Defer<F> {
fn drop(&mut self) {
(self.0)()
}
}
fn main() {
defer! { println!("coucou1"); println!(" (ending coucou1)"); };
defer! { println!("coucou2") };
println!("start");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment