1
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!

我很难理解这&*a意味着什么lifetime。我不知道*运算符如何与变量的生命周期相关。

好像 b 借了 x 也借了 a,所以不仅 x(即 *a) 不能移动或修改,也a不能使用。

编译器的错误信息是:b 借用了 a。

所以,我运行了第二个代码。据我了解,借来的数据不能重新分配、移动或丢弃。之前我特意做a了drop b,以确保它a的寿命应该比b's长。

但是,第二个代码仍然有效。

那么,我如何理解与 相关的生命周期&mut *a

4

2 回答 2

0

重要的误解出现在您的第一行代码中。错误不是 that bborrows a,而是 that bborrows *a,意思是它借用了 x。由于 Rust 会尽早降级并删除引用,因此只要您不尝试使用a. 但是,当使用 时a,编译器现在会警告您有一个双重可变引用:一个借用*a(基本上x)在变量a中,一个借用*a在变量 中b

清除后,您的第二段代码就有意义了。a可以删除,因为b只是*a用来借用x,并且x有足够长的生命周期来访问。

于 2020-12-28T12:48:22.743 回答
0
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.
于 2020-12-28T14:00:06.107 回答