Last active
May 12, 2017 11:25
-
-
Save uasi/22405e7049125223e9bb to your computer and use it in GitHub Desktop.
"defer" in Rust (virtually useless)
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
// rustc 1.0.0-nightly (44a287e6e 2015-01-08 17:03:40 -0800) | |
#![feature(unboxed_closures)] | |
#![feature(unsafe_destructor)] | |
macro_rules! defer { | |
($($body:stmt);* ;) => { | |
let __deferred = Deferred::new(|| { $($body);* ; }); | |
} | |
} | |
struct Deferred<F> { | |
finalize: F, | |
} | |
impl<F> Deferred<F> where F: FnMut() { | |
fn new(finalize: F) -> Deferred<F> { | |
Deferred { finalize: finalize } | |
} | |
} | |
#[unsafe_destructor] | |
impl<F> Drop for Deferred<F> where F: FnMut() { | |
fn drop(&mut self) { | |
#![allow(unstable)] | |
self.finalize.call_mut(()); | |
} | |
} | |
fn hello() { | |
defer! { println!("defer1"); } | |
defer! { println!("defer2"); } | |
print!("Hello, "); | |
defer! { println!("defer3"); } | |
println!("World!"); | |
} | |
fn main() { | |
hello(); | |
println!("done"); | |
} |
fn foo() {
let handle = MyHandle::new();
defer! { handle.close(); }
// You can't even touch the handle here
// as its mutable reference is trapped in the defer block :(
}
Check out https://github.com/bluss/scopeguard
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: