[英]How is synchronizing is a problem for multiple mutable references in Rust?
我正在閱讀 Rust 文檔第 4 節並看到這樣的代碼:
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
所以文檔說你不能在 Rust 中有多個可變引用。 好的,有道理,但 doc 說,如果您可以使用,會發生三種行為,其中一種是:
沒有用於同步數據訪問的機制。
是否需要機制來同步它? 我的意思是我們已經使用了指向堆或指向堆的另一個指針的指針。
我的意思是在這張圖中,假設我們有s2
和s3
作為對s1
可變引用。 s1
已經有一個指向堆的指針,所以s2
和s3
有指向 s1 的指針。 當我們改變s2
或s3
時,堆中的內存不會改變嗎?
let mut s1 = String::from("Hello");
let s2 = &mut s1;
s2.push_str(", world");
在這里, s1
指向的堆中的內存發生了變化,因此s3
已經指向該內存,所以它不是已經同步了嗎?
我只是假設我們可以有多個可變引用,我知道這種情況還有另一個問題,但根據 Rust 文檔的三個問題之一就是這個。
想象一下,如果允許以下內容:
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;
我們將能夠在安全的 Rust 中做各種未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.