RAII in Rust: Automatic Cleanup via Scope
RAII ties a resource's lifetime to its owner's scope. When the owner variable is dropped, Rust automatically cleans up the resource, preventing leaks. This applies to heap memory, file handles, and locks. The footgun: cleanup is deterministic, not like a GC.
WHY IT EXISTS Manual resource management is a major source of bugs. Forgetting to free memory, close a file, or release a lock leads to leaks, corruption, and deadlocks. RAII was adopted by Rust to make correct resource handling automatic and the default, eliminating these errors by design.
THE MENTAL MODEL Think of a variable as a temporary custodian for a resource. The rule is simple: when the custodian's job is done (i.e., it goes out of scope), it must return the resource. In Rust, this "returning" is an automatic cleanup process enforced by the compiler. You acquire the resource when you create the object, and it's released the moment the object is destroyed.
HOW IT WORKS When a value is created, it may acquire a resource, like allocating memory with Box::new. Rust tracks the "owner" of this value. When the owner goes out of scope (at the closing brace } of its block), Rust automatically calls the drop method for that value. Types can implement the Drop trait to define custom cleanup logic, such as closing a file or releasing a network socket. This cleanup is recursive: dropping a struct will drop all its fields.
WHEN TO USE IT RAII is the idiomatic, default behavior in Rust. You use it implicitly with most standard library types that manage resources. Common examples include Box<T> for heap memory, Vec<T> for dynamic arrays, File for file handles, and MutexGuard for locks. A MutexGuard automatically releases its lock when it goes out of scope, preventing deadlocks from forgotten unlocks.
WHEN NOT TO USE IT You typically only bypass simple RAII when the resource's lifetime must outlive a single lexical scope. For this, Rust provides shared ownership patterns like Rc (Reference Counted) and Arc (Atomic Reference Counted), which delay cleanup until the last reference is dropped. You also work outside of RAII when interfacing with C libraries via FFI, which requires manually calling C's free function within an unsafe block.
ONE CANONICAL EXAMPLE A Box is the classic example. When you write let my_box = Box::new(5);, you allocate an integer on the heap. If this is inside a function, my_box owns that memory. As soon as the function ends, my_box goes out of scope. Rust automatically calls its drop implementation, which frees the heap memory. You never write a free call; the cleanup is guaranteed by the language structure.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.