let a = &mut x;
a.somemethod(); // value of a should have moved
a.anothermethod(); // but it works.
我已经进行了大量的谷歌搜索(真的很多),并且我注意到作为参数传递给函数的可变引用,总是会经历以下转换(称为重新借用)。
fn test(&mut a) -> ();
let a = &mut x;
test(a); // what we write in code.
test(&mut *a); // the actual action in code.
所以,我对“reborrowing”进行了更详细的谷歌搜索。
以下是我找到的内容:
在任何代码中,x都指代任意数据。我没有提及它,因为我认为它的类型对讨论并不重要。(然而,在我的代码中我使用了i32)。
let a = &mut x;
let b = &mut *a; // a isn't available from now on
*a = blahblah; // error! no more access allowed for a
*b = blahblah; // I've wrote this code not to confuse you of the lifetime of b. If not mentioned, it always live till the scope ends.
let a = &mut x;
{
let b = &*a;
// *a = blahblah in this scope will throw an error, just like above case.
}
*a = blahblah; // but this works.
好的。这很有趣。看起来b
不仅借用了x
,还借用了a
。
也许,我们可以这样澄清重新借用:&'a *(&'b mut x)
。
它借用了x
(在此处有一个生命周期为'a'),
但也借用了a
(它的生命周期为'b')。
所以我运行了以下代码来确认我的猜想。
let x: i32 = 1; // I wanted to make it clear that x lives in this scope.
let b;
{
let a = &mut x;
b = &mut *a;
}
*b = 0;
但这可行!
什么??
但我刚决定使用&'a mut *&mutx
,而不是&'a mut *&'b mutx
。
我不知道为什么在&mut *&mutx
的生命周期内mut x
无法使用,也不知道为什么在&mut *&mutx
的生命周期之后mut x
又可以使用了,但“好吧,就这样吧”。
但看看这个。它完全超出了我的理解范围。
let x: i32 = 1;
let b;
{
let a = &mut x;
let b = &**&a;
} // error!! a should live longer than b!
生命周期不是简单地依赖于实际数据 b
所指的吗???
应该使用 &'a **& &mut x
,而不是 &'a **&'b &'c mut x
。
现在怎么办??
&'a **&'b &mut x
???(这是我的猜测)。
我应该如何接受这种复杂的情况呢?