Chapter 16: Ownership as Resource Management
Prerequisites
You will understand
- RAII — resource cleanup tied to scope exit
- Drop order (reverse declaration) and why it matters
- Why Rust rarely leaks resources without GC
Reading time
Resource Acquisition, Use, and Automatic Cleanup
Fields Drop in Reverse Declaration Order
If You Remember Only 3 Things
- Variables in Rust are not just names for data; they are deterministic resource managers.
- When an owning variable goes out of scope, Rust automatically calls the
Droptrait, instantly freeing the memory or closing the file. - This pattern is called RAII (Resource Acquisition Is Initialization), and it is why Rust rarely leaks resources even without a garbage collector.
Recommended Reading
- Rustonomicon: Ownership and Lifetimes
- Rust Book: The Drop Trait
- Codebase study: Look at how
std::fs::FileimplementsDropto automatically close file handles.
Before the readiness check, watch RAII happen. Step through the simulation below and observe the lifecycle: every scope exit deterministically frees exactly the resources that scope owns — no garbage collector, no manual free.
Interactive simulation (requires JavaScript): two String values are created in nested scopes; each is dropped and its heap buffer freed exactly when its own scope ends — the inner one at the inner closing brace, the outer one at the end of main. RAII ties cleanup to scope boundaries.
Readiness Check - Ownership Mastery
Use this quick rubric before moving on. Aim for at least Level 2 in each row.
| Skill | Level 0 | Level 1 | Level 2 | Level 3 |
|---|---|---|---|---|
| Explain ownership in plain English | I repeat rules only | I explain one-owner cleanup | I connect ownership to resource lifecycle | I can predict cleanup/transfer behavior in unfamiliar code |
| Spot ownership bugs in code | I rely on compiler messages only | I can identify moved-value mistakes | I can refactor to remove accidental moves | I can redesign APIs to avoid ownership friction |
| Reason about Drop and scope end | I treat Drop as magic | I know scope end triggers cleanup | I can explain reverse drop order and RAII implications | I can design deterministic teardown for complex structs |
If you are below Level 2 in any row, revisit the code reading drills in this chapter and Drill Deck 1.
Compiler Error Decoder - RAII and Drop
| Error code | What it usually means | Typical fix direction |
|---|---|---|
| E0382 | Value used after move during resource flow | Pass by reference when ownership transfer is not intended |
| E0509 | Tried to move out of a type that implements Drop | Borrow fields or redesign ownership boundaries for extraction |
| E0040 | Attempted to call Drop::drop directly | Use drop(value) and let Rust enforce one-time teardown |
If your cleanup logic feels complicated, model it as ownership transitions first, then encode it in API boundaries.