Recipe
Fix a borrow error
Use when: rustc stops the build with E0382, E0499, E0502, E0506, E0597, E0106 or E0515
Goal: a program that compiles and still does what it was meant to do
Taught in Fixing borrow errors
Quick recipe
-
1
Note the error code, then find the two parties in the labels: what was moved or borrowed first, and what collided with it.
Example
E0502 labels "immutable borrow occurs here" on line 3, "mutable borrow occurs here" on line 4, and "immutable borrow later used here" on line 5.
Why: every fix below targets one of the parties, so you need to know which is which.
-
2
Find the label that says "later used here" or "borrow later used here". That line is why the loan is still alive.
Why: a borrow lasts until its last use, so this line decides whether the two loans overlap.
-
3
Pick by what the program needs.
- the reader's last use can move above the writer — reorder.
- E0382 after passing a value to a function that only reads it — change the parameter to a reference and pass
&value. - the old value is needed after the change —
cloneit first, knowing it copies. - a reference would outlive its value (E0597, E0106, E0515) — return the owned value, or declare the owner in an outer scope.
- a reference must survive a change to its collection, or two loans share one line — keep an index, or split the line into steps.
Why: each fix removes one party or stops the overlap, which is what the rule was enforcing.
-
4
Build again, then check the output is what the program was for.
Why: some fixes compile but change what the program does, like reordering a push above the line that reads the old last item.
Common mistakes
- Reaching for
.clone()first, when a borrow or a reorder costs nothing. - Following rustc's
'statichint on E0106, which only moves the error into the body. - Adding
mutto a reference variable to fix E0597 or E0502; it changes neither the loan nor the value's life. - Reordering lines until it compiles without checking the output.