Fighting the Borrow Checker
Medium
+3 pts
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 …
Login to see the full exercise.
Topics