为什么创建对解除引用的可变引用的可变引用有效? [英] Why does creating a mutable reference to a dereferenced mutable reference work?
问题描述
我知道您不允许在 Rust 中同时创建两个对一个对象的可变引用.我不完全理解为什么以下代码有效:
I understand you're not allowed to create two mutable references to an object at once in Rust. I don't entirely understand why the following code works:
fn main() {
let mut string = String::from("test");
let mutable_reference: &mut String = &mut string;
mutable_reference.push_str(" test");
// as I understand it, this creates a new mutable reference (2nd?)
test(&mut *mutable_reference);
println!("{}", mutable_reference);
}
fn test(s: &mut String) {
s.push_str(" test");
}
推荐答案
规则
在任何时间点都只能有一个对特定值的可用可变引用.
There shall only be one usable mutable reference to a particular value at any point in time.
这不是空间排除(同一部分可以有多个引用),而是时间排除.
This is NOT a spatial exclusion (there CAN be multiple references to the same piece) but a temporal exclusion.
机制
为了强制执行此操作,&mut T
不是 Copy
;因此调用:
In order to enforce this, &mut T
is NOT Copy
; therefore calling:
test(mutable_reference);
应该将引用移动到test
.
实际上这样做会使其在以后无法使用并且不符合人体工程学,因此 Rust 编译器会插入一个自动重新借用,就像您自己做的那样:
Actually doing this would make it unusable later on and not be very ergonomic, so the Rust compiler inserts an automatic reborrowing, much like you did yourself:
test(&mut *mutable_reference);
如果您愿意,可以强制移动:
You can force the move if you wanted to:
test({ let x = mutable_reference; x });
效果
再借,本质上就是借:
mutable_reference
只要未命名的临时可变引用存在(或从它借用的任何东西),就会被借用,- 未命名的临时可变引用移入
test
, - 在表达式处,未命名的临时可变引用被销毁,因此
mutable_reference
的借用结束.
mutable_reference
is borrowed for as long as the unnamed temporary mutable reference exists (or anything that borrows from it),- the unnamed temporary mutable reference is moved into
test
, - at the of expression, the unnamed temporary mutable reference is destroyed, and therefore the borrow of
mutable_reference
ends.
这篇关于为什么创建对解除引用的可变引用的可变引用有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!