[−][src]Crate phantomdrop
Small library for defer
ing the running of function until the end of a block.
Uasge
Similar to the defer
mechanism in Go, we can use this to defer the calling of functions
fn do_something() { let _guard = phantomdrop::defer(|| println!("Hello!")); // do some work } // "Hello!" will now be printed when the function returns or unwinds (unless unwinds are disabled).
Values
The guard can also hold a value
fn do_something(print: String) { let _guard = PhantomDrop::new(print, |string| println!("Dropped: {}", string)); // do some work } // `print` will now be printed here.
Or capture a value, by reference, mutable reference, or moving.
fn do_something(print: String) { let _guard = phantomdrop::defer(move || println!("Dropped: {}", print)); // Moves `print` into itself. // do some work } // `print` will now be printed here. fn do_something_by_reference(print: String) { let _guard = phantomdrop::defer(|| println!("Dropped: {}", print)); // Holds an immutable reference to `print`. let trimmed = print.trim(); // Can still be used } // `print` will now be printed here. fn do_something_by_mutable_reference(print: &mut String) { let _guard = phantomdrop::defer(|| *print = String::from("Dropped")); // Holds a mutable reference to `print`. } // `print` will now be set to "Dropped" here.
Structs
PhantomDrop | When dropped, the included function is ran with the argument held by the structure. |
Functions
defer | Defer this function to run when the returned guard is dropped. |
Type Definitions
PhantomDropEmpty |
|
PhantomDropPure |
|