#type-system #container #callback #lambda #closure

drop_guard

The drop_guard crate enables you to implement the Drop trait on any type. So you can run a closure on any value running out of scope

7 unstable releases

new 0.3.0 Nov 24, 2021
0.2.1 Sep 23, 2017
0.1.0 Sep 1, 2017
0.0.2 Aug 8, 2017
0.0.1 Jul 13, 2017

#107 in Rust patterns

Download history 2423/week @ 2021-08-10 3595/week @ 2021-08-17 3293/week @ 2021-08-24 4229/week @ 2021-08-31 3749/week @ 2021-09-07 3712/week @ 2021-09-14 3782/week @ 2021-09-21 4060/week @ 2021-09-28 3747/week @ 2021-10-05 4263/week @ 2021-10-12 3680/week @ 2021-10-19 4699/week @ 2021-10-26 3655/week @ 2021-11-02 3763/week @ 2021-11-09 3860/week @ 2021-11-16 3140/week @ 2021-11-23

14,999 downloads per month

MIT/Apache

9KB
86 lines

drop_guard

crates.io doc.rs Build Status travis Build status appveyor

A RAII that executes you function whenever the wrapped object gets dropped.

Use cases

Joining threads when they fall out of scope:

extern crate drop_guard;

use drop_guard::DropGuard;

use std::thread::{spawn, sleep};
use std::time::guard;

fn main() {
    let _ = guard(spawn(move || {
                            sleep(Duration::from_secs(2));
                            println!("println! from thread");
                        })
                        , |join_handle| join_handle.join().unwrap());
    
    println!("Waiting for thread ...");
}

Examples

Feel free to run the included examples:

cargo run --example drop
cargo run --example rainbow
cargo run --example thread
cargo run --example threadpool

Contribute

Contributions are very welcome. Feel free to bring your own ideas or continue one of these:

  • Add example/test with panic between guard and drop
  • Add example/test with panic in guard closure
  • Add minimal rustc version

License

Licensed under either of

at your discression.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps