Doğukan Akkaya
Doğukan Akkaya

Reputation: 513

How is synchronizing is a problem for multiple mutable references in Rust?

I was reading Rust documentation section 4 and saw a code like this:

let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s;

println!("{}, {}", r1, r2);

So the documentation says that you cannot have multiple mutable references in Rust. Okay, makes sense but doc says three behaviors occurs if you could use, one of them is:

There’s no mechanism being used to synchronize access to the data.

Is there a need of mechanism to synchronize it? I mean we already use pointers to the heap or to another pointer that points to the heap.

rust-diagram

I mean in this diagram, let's say that we have s2 and s3 as mutable references to s1. s1 already has a pointer to the heap so s2 and s3 has pointers to s1. When we change s2 or s3 doesn't the memory change in the heap?

let mut s1 = String::from("Hello");
let s2 = &mut s1;
s2.push_str(", world");

In here the memory in the heap that s1 points to is changed so the s3 already points to that memory so doesn't it already synchronized?

I got the problem that why we should not use multiple mutable references. I just assume that we could. Rust says there is no mechanism to sync access to the data. My question is, we already have pointers to the heap from each reference so when we change the value in the heap it will all be synced because they are not values, they're just pointers to the heap and the value in the heap is changed?

Upvotes: 1

Views: 282

Answers (1)

Hadus
Hadus

Reputation: 1674

Imagine if the following was allowed:

let mut maybe_five = Some(5);
let mut zero = 0;

// first mutable borrow
let ref_five = &mut maybe_five;

// second mutable borrow
// number_ref is a reference inside maybe_five's Some
let number_ref = match &mut maybe_five {
    Some(ref mut five) => five,
    _ => &mut zero,
};

// invalidate number_ref by making the value it points to invalid
*ref_five = None;

// now we write into a None???
*number_ref = 10;

We would be able to do all kinds of undefined behavior in safe rust.

Upvotes: 1

Related Questions