scopeguard

Rust crate for a convenient RAII scope guard that will run a given closure when it goes out of scope, even if the code between panics (assuming unwinding panic).

The defer! macro and guard are no_std compatible (require only core), but the on unwinding / not on uwinding strategies requires linking to std.

Requires Rust 1.20.

Please read the API documentation here__

__ https://docs.rs/scopeguard/

|buildstatus| |crates|_

.. |buildstatus| image:: https://travis-ci.org/bluss/scopeguard.svg .. _buildstatus: https://travis-ci.org/bluss/scopeguard

.. |crates| image:: http://meritbadge.herokuapp.com/scopeguard .. _crates: https://crates.io/crates/scopeguard

How to use

.. code:: rust

#[macro_use(defer)] extern crate scopeguard;

use scopeguard::guard;

fn f() {
    defer!(println!("Called at return or panic"));
    panic!();
}

use std::fs::File;
use std::io::Write;

fn g() {
    let f = File::create("newfile.txt").unwrap();
    let mut file = guard(f, |f| {
        // write file at return or panic
        let _ = f.sync_all();
    });
    // Access the file through the scope guard itself
    file.write_all(b"test me\n").unwrap();
}

Recent Changes