Part of the kernel crate, a ScopeGuard is a wrapper around a function pointer which calls said function whenever the ScopeGuard instance stops being referenced.
It's useful for example to handle cleanups when a function has more complicated cleanup than just freeing memory or unlocking locks.
The user can call disarm on the ScopeGuard instance to prevent it from firing:
// Create an anonymous function to perform cleanup
let guard = ScopeGuard::new(|| {
... // Cleanup code
});
// --snip--
if some_condition() {
return; // guard goes out of scope, runs cleanup code
}
// --snip--
// When the function exits normally, the guard can be disarmed
guard.disarm();
return;
It's similar to defer in other languages, with the addition of being able to skip the defer closure execution if needed.
There's also a standalone scopeguard crate which accomplishes a similar behavior.
Source: