Hyunjik Bae
Hyunjik Bae

Reputation: 2939

One mutable borrowing or many immutable borrowings in Rust...why?

Why does Rust allow only one mutable borrowing or many immutable borrowings? Can its behavior be useful for preventing from bug-prone codes even in single-threaded programming? If it is, what is an example case?

Upvotes: 2

Views: 76

Answers (1)

cdhowie
cdhowie

Reputation: 169143

Yes, this helps prevent bugs in single-threaded cases. Consider this simple case:

let a = vec![1i32];

let b = &a[0]; // Borrows the first element of the Vec.

a.clear();

println!("{}", b); // Oops, the value b references doesn't exist anymore!

This fails to compile in Rust because a.clear() requires mutably borrowing a, but b is immutably borrowing it. Equivalent code would compile in C++ using std::vector, but would exhibit undefined behavior at runtime. (It's a common misconception that there's a problem with Rust when it rejects rewritten code from other languages like C++ where the original code compiled fine in that language, when, in fact, there was likely a memory safety issue in the original code that was undiscovered.)

Note that even a.push() could invalidate references obtained prior because it can require reallocating storage for the vec if the internal allocation has no more free capacity.

Mutably borrowing a value must exclude any other overlapping borrow because mutating a value can result in the invalidation of overlapping borrows of the same value.

Upvotes: 8

Related Questions