A scope guard will run a given closure when it goes out of scope, even if the code between panics. (as long as panic doesn't abort)
Examples
defer!
Use the defer
macro to run an operation at scope exit,
either regular scope exit or during unwinding from a panic.
extern crate scopeguard;
use Cell;
Scope Guard with Value
If the scope guard closure needs to access an outer value that is also mutated outside of the scope guard, then you may want to use the scope guard with a value. The guard works like a smart pointer, so the inner value can be accessed by reference or by mutable reference.
1. The guard owns a file
In this example, the scope guard owns a file and ensures pending writes are synced at scope exit.
extern crate scopeguard;
use File;
use ;
2. The guard restores an invariant on scope exit
extern crate scopeguard;
use ManuallyDrop;
use ptr;
// This function, just for this example, takes the first element
// and inserts it into the assumed sorted tail of the vector.
//
// For optimization purposes we temporarily violate an invariant of the
// Vec, that it owns all of its elements.
//
// The safe approach is to use swap, which means two writes to memory,
// the optimization is to use a “hole” which uses only one write of memory
// for each position it moves.
//
// We *must* use a scope guard to run this code safely. We
// are running arbitrary user code (comparison operators) that may panic.
// The scope guard ensures we restore the invariant after successful
// exit or during unwinding from panic.
Crate features:
use_std
- Enabled by default. Enables the
OnUnwind
strategy. - Disable to use
no_std
.
- Enabled by default. Enables the