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

Creates a new guarded object wrapping the given data and with the given cleanup function.

Prevents the cleanup function from running and returns the guarded data.

Creates a new guarded object with the given cleanup function.

Trait Implementations

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

This documentation is an old archive. Please see https://rust.docs.kernel.org instead.