简体   繁体   中英

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.

锈蚀图

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 just assume that we could have multiple mutable references, i know there are another problems for this case but one of the three problems according to Rust docs was this.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM