Function on_drop

Source
pub fn on_drop<F>(f: F) -> OnDrop<F>
where F: FnOnce(),
Expand description

Creates an object that will run the closure when it is dropped.

The closure will run even if the object is dropped during unwinding.

Running the closure can be cancelled by calling OnDrop::forget.

§Example: Object setup without RAII

use run_on_drop::on_drop;

let object = create_object();
let cleanup = on_drop(|| destroy_object(&object));
initialize_object(&object); // might unwind
cleanup.forget();
return object;

§Example: Resetting a flag

use core::cell::Cell;
use run_on_drop::on_drop;

let flag = Cell::new(false);

flag.set(true);
let _reset_flag = on_drop(|| flag.set(false));
f();