ownership

Rust RAII: tie cleanup to an owning guard

Resource Acquisition Is Initialization (RAII) ties a resource to an object that manages its release. Rust ownership and Drop make this pattern useful for locks, memory and file handles. The example uses a harmless logging guard, not an actual lock. Expected output (not executed): Acquire Work Release After work Why: The guard is owned by work and cleaned up as that function returns normally. Common mistake: Assuming a destructor can guarantee external cleanup even after abort or forced process termination.

Formal Syntax & Structure

rust syntaxrust
let guard = acquire();

Working Example

Example Snippetrust
struct Guard;impl Drop for Guard {    fn drop(&mut self) { println!("Release"); }}fn acquire() -> Guard {    println!("Acquire");    Guard}fn work() {    let _guard = acquire();    println!("Work");}fn main() {    work();    println!("After work");}
Rust Reference