Module 2Borrowing & ReferencesLesson 6 of 918 min
Reading Borrow Checker Errors
Hand-holding through the most common compile errors and how to fix them.
Error patterns you’ll see
1) Use after move
Fix: borrow, clone, or restructure.
2) Cannot borrow as mutable because also borrowed as immutable
Fix: finish read borrows before mut borrow; shrink scopes.
rust
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0]; // copy out i32
v.push(4); // ok — no live ref
println!("first={first} v={v:?}");
}Output
first=1 v=[1, 2, 3, 4]3) Returns reference to local
Fix: return owned data (String, Vec) instead of &str to locals.
Practical strategy
- Prefer owned fields in structs for long-lived data
- Prefer short borrows in function signatures
- Don’t fight the checker with
unsafewhile learning
Exercise
Fix the broken function in the starter (commented mistakes).
Challenge
Write fn longest<'a>(a: &'a str, b: &'a str) -> &'a str that returns the longer borrowed str.
Tips
- If data is created inside the function, return String not &str
- Split code into smaller scopes when mut/immut conflict
- The checker is teaching aliasing rules used by CPUs and compilers
Try it live
Reading Borrow Checker ErrorsRust 2021
Loading editor…
Output
Press Run to compile and execute.