Search code examples
pointerstypesrusttype-systems

Why does Rust enforce objects can only be mutably borrowed once?


Isn't there already Send/Sync? The official document only mentions it has something to do with data races.


Solution

  • Because of memory safety.

    Consider this example (disregard the fact that this would result in an infinite loop if it compiled):

    let mut list = vec![1, 2, 3];
    for item in &list {
        list.push(*item + 1);
        println!("item = {}", item);
    }
    

    item is a reference to the memory held by list; it is of type &i32. You may read the value of that element by dereferencing it (*item).

    What would happen to the reference in item if the push call were to reallocate the vector's memory to a different address?

    The reference would then contain the old address. Any attempt to access it would involve reading some undefined chunk of memory. This violates a core Rust safety principle.

    Isn't there already Send/Sync

    Send and Sync are concerned with multiple threads. As you can see from the example above, you don't need threads to potentially produce invalid references.