Fighting the Borrow Checker
In Python, you can freely mix reading and modifying data:
items = [1, 2, 3]
first = items[0] # read
items.append(4) # modify while holding reference
print(first) # works fine... usually
# But this can cause subtle bugs:
d = {"key": [1, 2]}
ref = d["key"] # reference to the list
d["key"] = [99] # replace the list
ref.append(3) # ref still points to old list!
Python catches some issues at runtime, but many aliasing bugs silently corrupt data. Rust catches ALL these at compile time with the borrow checker.
Every Rust beginner fights the borrow checker. The errors look cryptic at first, but they always point to real bugs that would cause crashes in other languages.
Error: "cannot borrow as mutable because it is also borrowed as immutable"
let mut v = vec![1, 2, 3];
let first = &v[0]; // immutable borrow
v.push(4); // ERROR: mutable borrow while immutable exists
println!("{}", first); // first is still in use
Why? push might reallocate the vector, invalidating first. Rust catches this at compile time; C would crash at runtime.
Fix: finish using the immutable borrow before mutating:
let mut v = vec![1, 2, 3];
let first = v[0]; // copy the value (i32 is Copy)
v.push(4); // now safe
println!("{}", first);
Error: "cannot move out of index"
let names = vec!["Alice".to_string()];
let first = names[0]; // ERROR: cannot move out of Vec
Why? Taking ownership of names[0] would leave a "hole" in the vector.
Fix: borrow or clone:
let first = &names[0]; // borrow
let first = names[0].clone(); // or clone to own
Error: "value borrowed here after move"
let s = String::from("hello");
let s2 = s; // s moved to s2
println!("{}", s); // ERROR: s was moved
Fix: clone if you need both:
let s = String::from("hello");
let s2 = s.clone();
println!("{} {}", s, s2);
The pattern: think about who needs what
Before writing code, ask: - Do I need ownership or just a view? - Am I done reading before I mutate? - Can I copy/clone to avoid borrow conflicts?
Login to see the full task and start coding.
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise