Week 3 - Ownership, Borrowing, and Region Inference¶
3.1 Conceptual Core¶
- Ownership is destructor scheduling: the owner is the entity that will run
Drop::drop. There is exactly one. - Borrowing is temporary capability delegation:
&Tgrants read capability,&mut Tgrants exclusive read+write capability. A capability cannot outlive the resource that backs it (the lifetime constraint). - Lifetimes are not durations. They are region variables that the compiler infers under a system of inequality constraints (
'a: 'bmeans region'aoutlives region'b). The compiler does not know "how long" anything lives in seconds-only the partial order of regions.
3.2 Mechanical Detail¶
- The three borrow-checker rules, stated formally:
- At any program point, for any place
p: at most one&mut por any number of&p, never both. - References must be valid for their entire region.
- The owner cannot mutate or move the value while a borrow is active (this is what NLL-non-lexical lifetimes-relaxed).
- Two-phase borrows (
v.push(v.len())): why this compiles even though it looks like aliasing. - Reborrowing:
&mut *rproduces a fresh&mutwith a shorter lifetime. This is the foundation for passing&mutreferences into functions repeatedly.
3.3 Lab-"Defeat the Borrow Checker, Then Submit"¶
You will be given (as exercise files) ten programs that the borrow checker rejects. For each:
1. Predict which rule is violated before reading the diagnostic.
2. Fix it three different ways (e.g., scope shrinking, split borrow, Cell/RefCell).
3. Pick the idiomatic fix and justify it in a one-line comment-but only if the comment captures non-obvious reasoning. (See feedback rule on comments.)
3.4 Idiomatic & Clippy Drill¶
clippy::needless_lifetimes,clippy::redundant_clone,clippy::ptr_arg. The first two are about elision; the third is about API ergonomics.
3.5 Production Hardening Slice¶
- Run
cargo clippy --workspace --all-targets -- -D warningsin CI from week 1 forward. This is non-negotiable.