3 ms·
The borrow checker statically prevents having mutation and aliasing at the same time. Aliasing is when two names refer to the same state; mutable aliases make i
by Twisol 4y ago
The borrow checker statically prevents having mutation and aliasing at the same time. Aliasing is when two names refer to the same state; mutable aliases make it possible for "someone else" to act on that state while you're using it.
Consider the humble for-each loop:
for (let x : xs) {
xs.remove(0);
}
If you're not careful, modifying a collection while you're traversing it can cause you to visit elements multiple times, or skip some elements entirely. There are effectively two tasks occurring at the same time -- interleaved, not parallel, but still concurrent: the ordered traversal and the action on each element. Both tasks can view the list, but one of them also modifies it behind the other's back.
This problem simply can't happen in Rust (without going out of your way, at least), because you can't independently mutate a list you're already iterating over.