RAII / drop guards
RAII ties a resource to a value. The constructor acquires; Drop releases. A drop guard is a small type whose only job is that destructor, even if you forget every other path.
Detailed Explanation
RAII means resource acquisition is initialisation. File::open returns a File that closes itself. Mutex::lock returns a guard that unlocks itself. You do not pair open with close on every return and ?. The compiler inserts the close.
A drop guard is the same idea extracted into a helper. You need to temporarily set a flag, increment a counter, or restore a working directory. Write a struct that holds the old state and restores it in Drop. let _guard = DisableLogs::new(); then a function that can ? or panic, and the logs come back. The _ prefix is conventional: you do not use the value, you use its lifetime.
defer crates exist (scopeguard) for one-off closures. A named type is better when the guard is part of your API (MutexGuard is a named RAII type). Do not implement Drop on a large business object just to log; that runs on panic paths and surprises readers.
Async cancellation is RAII too. Dropping a future drops its guards. A guard that must not run on cancel needs a flag you set only on the success path, or a ManuallyDrop you forget when the resource was handed off.
When you write a guard: temporary state, locks, file descriptors, buffer swaps. When you write a manual close: you are about to miss a ? path. When the resource is memory only: Vec already dropped it.
Guards should be small enough to read in one screen. If the Drop impl grows a retry loop and a log of network calls, you have put a shutdown procedure in a destructor and it will run at surprising times, including panic and cancellation. Move ambitious cleanup to an explicit shutdown that returns Result, and let Drop call a best-effort version.
Code Examples
struct Span(&'static str);
impl Drop for Span {
fn drop(&mut self) {
println!("end {}", self.0);
}
}
fn work() -> Result<(), &'static str> {
let _span = Span("save");
println!("saving");
Ok(())
}
fn main() {
work().unwrap();
// prints:
// saving
// end save
}Common Gotchas
Prefix unused guards with `_`
`let guard = ...` without the underscore may warn. `let _ = guard` drops immediately — that is the opposite of what you want. Write `let _guard`.
A panic in `Drop` aborts during unwind
Guards must not panic. Restoration should be infallible.
Cancellation drops guards
In async code, that is usually what you want for locks. It is not what you want for "commit" actions; split commit from the guard.