[][src]Macro fungus::defer

macro_rules! defer {
    ($($tokens:tt)*) => { ... };
}

Ensure the given closure is executed once the surrounding scope closes despite panics. Inspired by Golang's defer, Java's finally and Ruby's ensure.

This provides a mechanism similar to Golang's defer that will trigger when the surrounding function goes out of scope.

Examples

use fungus::prelude::*;

let tmpdir = PathBuf::from("tests/temp").abs().unwrap().mash("core_defer_doc");
assert!(sys::remove_all(&tmpdir).is_ok());
assert!(sys::mkdir(&tmpdir).is_ok());

// Create a scope that will trigger finally's destructor
{
    defer!(sys::remove_all(&tmpdir).unwrap());
}
assert_eq!(tmpdir.exists(), false);