Mutable references have one big restriction: if you have a mutable reference to a value, you can have no other references to that value.
这样设计的动机如下:
The restriction preventing multiple mutable references to the same data at the same time allows for mutation but in a very controlled fashion. It’s something that new Rustaceans struggle with because most languages let you mutate whenever you’d like. The benefit of having this restriction is that Rust can prevent data races at compile time.
这原来就是为了并行编程吗?
不仅多个可改引用不能并存,可改引用与不可改引用也不能并存:
We also cannot have a mutable reference while we have an immutable one to the same value.Users of an immutable reference don’t expect the value to suddenly change out from under them! However, multiple immutable references are allowed because no one who is just reading the data has the ability to affect anyone else’s reading of the data.
不过引用的作用域其实是比较灵活的:
Note that a reference’s scope starts from where it is introduced and continues through the last time that reference is used.
the compiler can tell that the reference is no longer being used at a point before the end of the scope.Even though borrowing errors may be frustrating at times, remember that it’s the Rust compiler pointing out a potential bug early (at compile time rather than at runtime) and showing you exactly where the problem is. Then you don’t have to track down why your data isn’t what you thought it was.