Why Does Rust Enforce the "One Mutable or Many Immutable References" Rule in Single-Threaded Programs?

I read the blog post and found out a situation where this rule ensures memory safety even in single-threaded program!

fn push_all(from: &Vec<i32>, to: &mut Vec<i32>) {
    for i in from.iter() {
        to.push(*i);
    }
}

fn my_function() {
    let mut vec = vec![1,2,3];
    push_all(&vec, &mut vec);
}

This would spell disaster! As we're pushing elements onto the vector, it will occasionally need to resize, allocating a new hunk of memory and copying its elements over to it. The iterator would be left with a dangling pointer into the old memory, leading to memory unsafety (with attendant segfaults or worse).

Fortunately, Rust ensures that whenever a mutable borrow is active, no other borrows of the object are active, producing the message:

error: cannot borrow `vec` as mutable because it is also borrowed as immutable
push_all(&vec, &mut vec);
                    ^~~
1 Like