Struct kernel::types::ScopeGuard
source · [−]pub struct ScopeGuard<T, F: FnOnce(T)>(_);
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
sourceimpl<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.
Trait Implementations
sourceimpl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F>
impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F>
sourceimpl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F>
impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F>
Auto Trait Implementations
impl<T, F> RefUnwindSafe for ScopeGuard<T, F> where
F: RefUnwindSafe,
T: RefUnwindSafe,
impl<T, F> Send for ScopeGuard<T, F> where
F: Send,
T: Send,
impl<T, F> Sync for ScopeGuard<T, F> where
F: Sync,
T: Sync,
impl<T, F> Unpin for ScopeGuard<T, F> where
F: Unpin,
T: Unpin,
impl<T, F> UnwindSafe for ScopeGuard<T, F> where
F: UnwindSafe,
T: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more