Recipe
Find the line that frees each value
Use when: a program makes heap values such as Strings, and you need to say on which line each buffer goes back
Goal: for each owner, the closing brace that drops its value, and the order of the drops at a shared brace
Taught in The ownership rules · a later section extends this recipe with more cases
Quick recipe
-
1
Write down each variable, made by a
let, that holds a heap value. A tuple is one owner for everything inside it.Example
In the
cityandbandprogram, the owners arecityandband. Each one holds oneString.Why: rule 3 is about owners, so the owners are what you track.
-
2
For each owner, find its
let. Then find the}that closes the block thatletsits in.Example
bandis made inside the inner block, so its brace is the}on line 6.cityis made inmain's body, so its brace is on line 8.- the
letis inside an inner block, such as anifbody or a bare{ }— the brace is that block's}. - the
letis right in the function's body — the brace is the function's last}.
- Not yet: the value is handed to another variable or into a function — covered in Predicting moves
Why: the owner goes out of scope at that brace, and rule 3 drops its value there.
- the
-
3
When two or more owners end at the same
}, they are dropped in reverse order of theirlets. The last one made goes first.Example
In a
mainwithlet a = ...;and, further down,let c = ...;, both end atmain's}.cis dropped first, thena.Why: Rust cleans up a block the way the stack (Chapter 6) works: newest first.
-
4
When an owner is dropped, every value it holds is dropped with it.
Example
let menu = (String::from("tea"), String::from("cake"));has one owner and two buffers. Both buffers are freed atmain's}, whenmenuis dropped.Why: ownership forms a tree, and dropping the top of it drops everything underneath.
Common mistakes
- Counting variables instead of buffers. Count the
String::fromcalls to count buffers. - Picking the function's last brace for a
letthat sits inside an inner block. - Dropping owners at a shared brace in the order they were written. It runs the other way.
- Thinking you must free the
Strings inside a tuple yourself.