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
35 min
+ 20 min exercises
Builds on Chapter 10
Ch 10 taught the three ownership rules. This chapter shows the engineering consequence: ownership IS resource management. Scope end IS cleanup.
Revisit Ch 10 →
You'll need this for Chapter 20
Move semantics, Copy, Clone, and Drop are the four transfer events that express what ownership means at each step.
Ch 20: Move/Copy/Clone/Drop →
RAII Lifecycle
Resource Acquisition, Use, and Automatic Cleanup
Drop Order
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.
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.