Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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:

  1. 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 open and close calls.

  2. 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
}
  1. 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.”