#closures #callback #lambda #container #type-system

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

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

#838 in Rust patterns

Download history 1791/week @ 2023-12-13 2552/week @ 2023-12-20 1000/week @ 2023-12-27 2304/week @ 2024-01-03 2519/week @ 2024-01-10 2864/week @ 2024-01-17 2676/week @ 2024-01-24 1536/week @ 2024-01-31 1581/week @ 2024-02-07 2348/week @ 2024-02-14 2497/week @ 2024-02-21 2623/week @ 2024-02-28 1969/week @ 2024-03-06 2570/week @ 2024-03-13 2396/week @ 2024-03-20 1892/week @ 2024-03-27

9,249 downloads per month
Used in 3 crates

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