RAII, Guards, and Drop Bombs
In Rust, cleanup is the type’s job rather than the caller’s. Drop runs
when a value goes out of scope, on every path, including early returns and
?.
Three uses, in increasing strength:
-
Resource cleanup. Files close, sockets shut down, and locks release when their owners are dropped. Generated code inherits this if resources are modeled as owned values instead of raw handles with paired
openandclosecalls. -
Scope guards. Run something on exit, whatever exit looks like:
pub struct BusQuiet<'a>(&'a BusController); // constructor pauses traffic
impl Drop for BusQuiet<'_> {
fn drop(&mut self) { self.0.resume(); } // resume cannot be forgotten
}
- Drop bombs. A guard that panics if dropped without being defused. It says: this transaction must be explicitly committed or rolled back, not forgotten. It’s an assertion about the caller’s control flow.
In review, search generated code for paired manual calls, such as begin
and end, acquire and release, or pause and resume, where the
caller must remember to call the second one. Any early return or ?
between the paired calls skips the second one. The prompt: “return a guard from begin whose Drop performs
end, and remove the manual end.”