Borrow conflicts and shorter borrows
Quick answer
Borrow conflicts happen when accesses overlap in ways that violate Rust's borrowing rules. Often the fix is to finish a shared read before starting a mutable borrow instead of making an unnecessary clone.
Last use matters
Rust can infer that a borrow ends after its last relevant use, even before the enclosing block ends. This is part of non-lexical lifetimes. If the shared reference is used again after a mutation, it may conflict with the mutable access. Reorder operations or retain only an independent result such as a copied length.
fn main() { let mut text = String::from("go"); let view = &text; println!("{view}"); text.push('!'); println!("{text}");}Expected stdout (not executed):
gogo!The view is not used after the mutation; the borrow can end before push.
fn main() { let mut text = String::from("go"); let view = &text; text.push('!'); println!("{view}");}Expected: compilation fails; exact diagnostic not verified.
The last use of view occurs after push; this example is rejected.
Common mistake
Do not reason only from opening and closing braces. The actual uses of references matter too.
Try it yourself
Fix the intentionally invalid example by printing view first. Then try storing its length before mutating.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Borrow conflicts and shorter borrows — practice quiz
Choose one answer per question, then review the explanation.
Must a shared borrow last until the enclosing block closes?
You copy `s.len()` to n, then modify s. Does n borrow s?
What change makes a read-then-write sequence possible without cloning?