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

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
RAII Lifecycle

Resource Acquisition, Use, and Automatic Cleanup

Manual C lifecycle Rust RAII lifecycle conn = open(); use(conn); did we close on every path? leak / double-close / early-close risk let conn = Connection::new(); use(&conn); scope ends → Drop::drop() resource closed exactly once
RAII matters because it ties cleanup to ownership instead of to developer memory. The scope boundary becomes a lifecycle boundary.
Drop Order

Fields Drop in Reverse Declaration Order

struct Server listener: TcpListener cache: HashMap logger: Logger 1. logger 2. cache 3. listener

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 Drop trait, 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.

Readiness Check - Ownership Mastery

Use this quick rubric before moving on. Aim for at least Level 2 in each row.

SkillLevel 0Level 1Level 2Level 3
Explain ownership in plain EnglishI repeat rules onlyI explain one-owner cleanupI connect ownership to resource lifecycleI can predict cleanup/transfer behavior in unfamiliar code
Spot ownership bugs in codeI rely on compiler messages onlyI can identify moved-value mistakesI can refactor to remove accidental movesI can redesign APIs to avoid ownership friction
Reason about Drop and scope endI treat Drop as magicI know scope end triggers cleanupI can explain reverse drop order and RAII implicationsI 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 codeWhat it usually meansTypical fix direction
E0382Value used after move during resource flowPass by reference when ownership transfer is not intended
E0509Tried to move out of a type that implements DropBorrow fields or redesign ownership boundaries for extraction
E0040Attempted to call Drop::drop directlyUse 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.

Step 1 - The Problem