Struct kernel::types::ScopeGuard
source · pub struct ScopeGuard<T, F: FnOnce(T)>(/* private fields */);
Expand description
Runs a cleanup function/closure when dropped.
The ScopeGuard::dismiss
function prevents the cleanup function from running.
Examples
In the example below, we have multiple exit paths and we want to log regardless of which one is taken:
fn example1(arg: bool) {
let _log = ScopeGuard::new(|| pr_info!("example1 completed\n"));
if arg {
return;
}
pr_info!("Do something...\n");
}
In the example below, we want to log the same message on all early exits but a different one on the main exit path:
fn example2(arg: bool) {
let log = ScopeGuard::new(|| pr_info!("example2 returned early\n"));
if arg {
return;
}
// (Other early returns...)
log.dismiss();
pr_info!("example2 no early return\n");
}
In the example below, we need a mutable object (the vector) to be accessible within the log
function, so we wrap it in the ScopeGuard
:
fn example3(arg: bool) -> Result {
let mut vec =
ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
vec.try_push(10u8)?;
if arg {
return Ok(());
}
vec.try_push(20u8)?;
Ok(())
}
Invariants
The value stored in the struct is nearly always Some(_)
, except between
ScopeGuard::dismiss
and ScopeGuard::drop
: in this case, it will be None
as the value
will have been returned to the caller. Since ScopeGuard::dismiss
consumes the guard,
callers won’t be able to use it anymore.
Implementations§
source§impl<T, F: FnOnce(T)> ScopeGuard<T, F>
impl<T, F: FnOnce(T)> ScopeGuard<T, F>
sourcepub fn new_with_data(data: T, cleanup_func: F) -> Self
pub fn new_with_data(data: T, cleanup_func: F) -> Self
Creates a new guarded object wrapping the given data and with the given cleanup function.