1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-30 01:16:17 +02:00
Nicole L 0c23d817e5
Add examples of the borrow checker catching errors (#2000)
I think it'd be helpful to actually demonstrate to students how the
"sharing XOR mutability" rule actually prevents errors in practice,
since right now we explain the rule but don't give much context as to
why the rule is important.
2024-04-19 10:19:06 -04:00

777 B

minutes
3

Borrow Errors

As a concrete example of how these borrowing rules prevent memory errors, consider the case of modifying a collection while there are references to its elements:

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];
    let elem = &vec[2];
    vec.push(6);
    println!("{elem}");
}

Similarly, consider the case of iterator invalidation:

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];
    for elem in &vec {
        vec.push(elem * 2);
    }
}
  • In both of these cases, modifying the collection by pushing new elements into it can potentially invalidate existing references to the collection's elements if the collection has to reallocate.