很难管理引用和取消引用的组合


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.

所以,我运行了第二个代码。根据我的理解,借用的数据不能被重新分配、移动或删除。我故意让ab之前下降,以确保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.

最新更新