Skip to content

Instantly share code, notes, and snippets.

@uasi
Last active May 12, 2017 11:25
Show Gist options
  • Save uasi/22405e7049125223e9bb to your computer and use it in GitHub Desktop.
Save uasi/22405e7049125223e9bb to your computer and use it in GitHub Desktop.
"defer" in Rust (virtually useless)
// 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");
}
@uasi
Copy link
Author

uasi commented Jan 14, 2015

Output:

Hello, World!
defer3
defer2
defer1
done

@uasi
Copy link
Author

uasi commented Jan 14, 2015

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 :(
}

@pronebird
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment