let mut x = 1;
let a = &mut x;
let b = &mut *a;
*a = 2; // error. b borrows a
*b = 3; // it works! (only without " *a = 2 ")
let mut x = 1;
let b;
{
let a = &mut x;
b = &mut *a;
} // a drops here
*b = 2; // it works!
在lifetime
的意义上,我很难理解&*a
的含义。我不知道*
算子和变量的寿命有什么关系。
看起来b借用了x和a,因此不仅x(即*a(不能移动或修改,而且a
也不能使用。
编译器的错误消息是:b借用a.
所以,我运行了第二个代码。根据我的理解,借用的数据不能被重新分配、移动或删除。我故意让a
在b
之前下降,以确保a
的寿命应该比b
的更长。
然而,第二个代码仍然有效。
那么,我该如何理解经历与&mut *a
相关的一生呢?
重要的误解是在您的第一行代码中。错误不是b
借用a
,而是b
借用*a
,意思是它借用了x。由于Rust尽可能早地降级和删除引用;双";只要不尝试使用a
,就允许使用可变引用。但是,当使用a
时,编译器现在会警告您有一个双可变引用:一个在变量a
中借用*a
(基本上是x
(,另一个在变数b
中借用*a
。
清除了这些之后,您的第二段代码就有意义了。a
可以被丢弃,因为b
只是在使用*a
借用x
,而x
有足够长的生存期可以访问。
let mut x = 1;
let a = &mut x; // now a is the mutable owner of x
let b = &mut *a; // *a -> x so, now b is the mutable owner of x
*a = 2; // it will not work as a is not the current mutable owner of x
*b = 3; // it will work as a is the current mutable owner of x
let mut x = 1;
let b;
{
let a = &mut x; // now a is the mutable owner of x
b = &mut *a; // *a -> x so, b is the mutable owner of x
} // a dropped but not x
*b = 2; // it will work because b is the current mutable owner of x and x is still in scope.