Borrowing and References
`&` and `&mut`, the one-writer-or-many-readers rule, non-lexical lifetimes, dangling references, slices and `&str`.
16 questions
JuniorTheoryCommonWhat does the program print (lines separated by spaces)?
What does the program print (lines separated by spaces)?
hi hi!
Open full question →Common mistakes
- ✗Expecting a compile error: a borrow lasts until the reference's last use, not to the end of the block, so
r1is done beforer2is created. - ✗Expecting the borrow rules to be checked while the program runs: the compiler checks them, and here the shared and the mutable borrow never overlap.
Follow-up questions
- →What happens if
r1is printed once more afterr2.push('!')? - →Why may the last line read
swhile the variabler2is still in scope?
JuniorTheoryCommonWhat does the program print?
What does the program print?
hello 5
Open full question →Common mistakes
- ✗Expecting a compile error:
len(&s)passes a reference, not theString, so ownership stays withsandprintln!may still use it. - ✗Expecting the string to be freed when
lenreturns: only the reference goes away, because the ownersis the one that frees the string.
Follow-up questions
- →How would the program change if
lentooks: Stringinstead of&String? - →Why is
&stra better parameter type than&Stringforlen?
JuniorTheoryCommonWhat are the borrowing rules, and which bugs does an exclusive &mut T prevent?
What are the borrowing rules, and which bugs does an exclusive &mut T prevent?
At any moment a value has either any number of shared &T or exactly one &mut T, and every reference points to a live value. A writer never coexists with readers, so code with iterator invalidation or a data race does not compile.
Common mistakes
- ✗Thinking several
&mutto one value are fine as long as the code runs in one thread - ✗Believing the borrow rules are enforced by run-time checks rather than by the compiler
- ✗Forgetting that even the owner cannot read the value while a
&mutto it is live
Follow-up questions
- →Why does
v.push(4)fail to compile while a reference&v[0]is still in use? - →How do the marker traits
SendandSyncextend the same rule to threads?
JuniorTheoryCommonWhat is a dangling reference, and how does Rust stop a function returning one?
What is a dangling reference, and how does Rust stop a function returning one?
A dangling reference points to memory that was already freed. A String created in a function is dropped when it returns, so a &str into it fails to compile (E0106 or E0515); return the owned String instead.
Common mistakes
- ✗Trying to fix E0106 with
'static, which does not make a local value live longer - ✗Expecting Rust to catch dangling references at run time instead of at compile time
- ✗Assuming a returned reference keeps its value alive, as a garbage collector would
Follow-up questions
- →When may a function return a
&strthat borrows from one of its parameters? - →Why does writing
-> &'static Stringturn the E0106 error into E0515?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
2: a reference does not keep its value alive, andsis dropped whenmakereturns, so the compiler refuses-> &Stringwith E0106. - ✗Expecting garbage or an empty string at run time: safe Rust never reads freed memory, because a dangling reference does not get past the compiler.
Follow-up questions
- →How would you change
makeso that the program compiles and prints2? - →Which error appears if the signature is changed to
-> &'static String?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
hi!: a&mutcannot be taken from a binding declared withoutmut, so the build stops with E0596 and the compiler asks forlet mut s. - ✗Expecting a copy of
sto be changed: a&mutpoints tositself, and the compiler refuses it becauselet spromised the value would not change.
Follow-up questions
- →What is the difference between
let mut r = &s;andlet r = &mut s;? - →Which single change makes this program compile and print
hi!?
JuniorTheoryCommonWhat does the program print?
What does the program print?
world hello
Open full question →Common mistakes
- ✗Expecting
world hell:a..bincludesaand stops just beforeb, so0..5takes indices 0 to 4, all five letters ofhello. - ✗Expecting a compile error for two slices of one
String: both are shared borrows, and the rules allow any number of&at once.
Follow-up questions
- →What would
&s[0..=5]contain, and how would the output change? - →Why does
&s[0..1]panic whensholds Cyrillic text?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
hi!?:r1is used afterr2is created, so two&muttosare alive at once, and the compiler stops with E0499. - ✗Expecting the second
&mutto take over quietly: Rust never invalidates a reference behind your back; overlapping&mutborrows are a compile error.
Follow-up questions
- →How would you reorder the lines so that the program compiles and prints
hi!?? - →Why is a second
&mutrefused even when the program has only one thread?
MiddleTheoryCommonWhat does the borrow checker verify, and how does it decide a borrow is still live?
What does the borrow checker verify, and how does it decide a borrow is still live?
It checks that no reference outlives its value and no access conflicts with a live borrow. A borrow is live from its creation to the reference's last possible use on any path; since a &mut is never shared, two threads cannot race.
Common mistakes
- ✗Believing a borrow lasts until the end of the enclosing block
- ✗Thinking the borrow checker adds run-time checks or reference counts
- ✗Assuming freedom from data races needs a separate tool rather than following from an exclusive
&mut
Follow-up questions
- →Why can a borrow be live on one branch of an
ifand dead on the other? - →Which safe programs does the borrow checker still reject, and how do you work around them?
MiddleDebuggingCommonFix a loop that pushes into the Vec it iterates over (E0502)
Fix a loop that pushes into the Vec it iterates over (E0502)
nums.iter() keeps the vector borrowed for the whole loop, while push needs &mut and may reallocate the buffer the iterator reads. Collect the doubles first and extend afterwards, or index over 0..len fixed beforehand.
Common mistakes
- ✗Thinking
iter_mut()allows pushing into the vector during the loop - ✗Blaming the reference type of the loop variable instead of the borrow on the vector
- ✗Forgetting that
pushmay move the buffer, which is why the rejection is necessary
Follow-up questions
- →Why does
nums.push(nums.len() as i32)compile although it reads and writesnums? - →How would the fix change if the loop had to remove the odd elements instead?
MiddleTheoryCommonWhat does a slice borrow, and why is a &s[a..b] range counted in bytes?
What does a slice borrow, and why is a &s[a..b] range counted in bytes?
A slice is a pointer plus a length into a Vec, array or String; it borrows the source, so the owner cannot change while it lives. A str is UTF-8 bytes, so &s[a..b] takes byte offsets and panics if one lands inside a character.
Common mistakes
- ✗Treating a slice as a copy that leaves the source free to change
- ✗Expecting
&s[0..1]to return the first letter of a non-ASCII string - ✗Using
len()as a character count when computing range ends
Follow-up questions
- →How do you take the first character of a
&strwithout risking a panic? - →Why are
&mut v[..2]and&mut v[2..]rejected together, and what doessplit_at_mutgive?
JuniorCodeOccasionalAppend to and uppercase a caller's Vec<String> through &mut
Append to and uppercase a caller's Vec<String> through &mut
Take names: &mut Vec<String>, call push, then loop over names.iter_mut() assigning *name = name.to_uppercase(). The caller passes &mut names; ownership never moves, so main prints the changed vector afterwards.
Common mistakes
- ✗Taking
Vec<String>by value and then finding that the caller's variable has been moved - ✗Iterating with
iter()and trying to assign through a shared&String - ✗Forgetting the
*when replacing an element through&mut String
Follow-up questions
- →Why can't the loop use
for name in names.iter()to change the entries? - →When would a function take
&mut [String]instead of&mut Vec<String>?
MiddleTheoryOccasionalWhat did non-lexical lifetimes change, and which code compiles only because of them?
What did non-lexical lifetimes change, and which code compiles only because of them?
Non-lexical lifetimes (Rust 2018) end a borrow at the reference's last use, not at the end of its block. So let f = &v[0]; let x = *f; v.push(x); now compiles; before, f stayed borrowed to the block end and push was E0502.
Common mistakes
- ✗Thinking non-lexical lifetimes let a reference stay usable across a conflicting
push - ✗Confusing non-lexical lifetimes with lifetime elision in function signatures
- ✗Believing the compiler now tracks borrows at run time
Follow-up questions
- →Which conditional return of a borrow does the checker still reject today?
- →How does the borrow-checker rule of two-phase borrows let
v.push(v.len())compile?
MiddleDesignOccasionalYou review a pull request in a Rust service that parses log lines into records. To silence borrow-checker errors, the author added .clone() to most String arguments, including calls to helpers that only read them; cloned a whole Vec before a loop that pushes into it; and spelled out lifetimes such as fn key<'a>(line: &'a str) -> &'a str on every function. A Record<'a> struct borrows &'a str fields from the per-line read buffer, so sending records to a long-lived cache needed yet another clone of the buffer. The tests pass, but allocations per line tripled. Constraints: 200k lines per second, records must outlive the buffer they were parsed from, and the code must stay readable for junior developers. What do you look for in the review, which clones and annotations do you remove or keep, and when is a clone the right fix?
You review a pull request in a Rust service that parses log lines into records. To silence borrow-checker errors, the author added .clone() to most String arguments, including calls to helpers that only read them; cloned a whole Vec before a loop that pushes into it; and spelled out lifetimes such as fn key<'a>(line: &'a str) -> &'a str on every function. A Record<'a> struct borrows &'a str fields from the per-line read buffer, so sending records to a long-lived cache needed yet another clone of the buffer. The tests pass, but allocations per line tripled. Constraints: 200k lines per second, records must outlive the buffer they were parsed from, and the code must stay readable for junior developers. What do you look for in the review, which clones and annotations do you remove or keep, and when is a clone the right fix?
Ask what each clone hides: read-only parameters should take &str or &[T], borrows should end before mutation, and annotations elision infers can go. A clone is right when data must outlive its source, like a cached record owning Strings.
Common mistakes
- ✗Believing
String::clonecopies only the header, not the heap bytes - ✗Thinking extra lifetime annotations change behaviour or speed rather than just describe borrows
- ✗Rejecting every clone, even where an owned copy has to outlive its source
Follow-up questions
- →When is the clone-on-write type
Cow<str>better than both cloning and borrowing? - →How do you tell which lifetime annotations the elision rules would already infer?
SeniorTheoryOccasionalWhat does the next-generation borrow checker Polonius accept that the non-lexical lifetimes analysis NLL rejects?
What does the next-generation borrow checker Polonius accept that the non-lexical lifetimes analysis NLL rejects?
Conditionally returning a borrow: if let Some(v) = map.get(&k) { return v; }, then map.insert(k, s). Returning v stretches its lifetime over every path to the end, so NLL calls insert E0502; Polonius tracks loans per path and accepts it.
Common mistakes
- ✗Believing Polonius already ships in stable rustc
- ✗Thinking NLL rejects borrows of disjoint struct fields, which it already accepts
- ✗Explaining the rejection as a run-time aliasing problem rather than a lifetime that spans every path
Follow-up questions
- →How do you rewrite the
get-then-insertfunction so it compiles on stable Rust today? - →Why is the conditional-return case sound even though NLL refuses it?
SeniorDebuggingOccasionalFix a method whose returned &String keeps the &mut self borrow alive
Fix a method whose returned &String keeps the &mut self borrow alive
The &String returned by a &mut self method reborrows that &mut, so cache stays exclusively borrowed while v is used, and cache.len() is E0502. Split the API: a &mut self method that inserts, then a &self getter for the value.
Common mistakes
- ✗Assuming a shared reference returned from a
&mut selfmethod downgrades the borrow to shared - ✗Trying to give the returned reference a lifetime unrelated to
self - ✗Blaming
HashMap::entryinstead of the method signature
Follow-up questions
- →Why can't the compiler downgrade the
&mut selfborrow to shared once the method returns? - →How would returning
(&String, usize)from the method change the call site?