Struct kernel::ScopeGuard[][src]

pub struct ScopeGuard<T: FnOnce()> { /* fields omitted */ }
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;
    }

    // Do something...
}

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");
}

Implementations

Creates a new cleanup object with the given cleanup function.

Prevents the cleanup function from running.

Trait Implementations

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

Performs the conversion.

Performs the conversion.

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.