When I wondered how a mutable reference could move into a method, all the questions began.
let a = &mut x;
a.somemethod(); // value of a should have moved
a.anothermethod(); // but it works.
I've googled a lot. (really a lot) And I've noticed that a mutable reference passed as a parameter to a function, always undergoes the following transformation. (which is called reborrowing)
fn test(&mut a) -> ();
let a = &mut x;
test(a); // what we write in code.
test(&mut *a); // the actual action in code.
So, I have googled more about "reborrowing", for its detail.
And this is what I've got.
In any of codes, x refers to an arbitrary data. I don't mention it because I don't think the type of it is important for discussion. (However, I used i32 in my own).
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.
So alright. It's quite interesting. It seems like b
borrows not only x
but also a
.
Perhaps, we can clarify reborrowing like this : &'a *(&'b mut x)
.
It has borrowed x
(which has a lifetime 'a in here),
but also borrowed a
(which has a lifetime 'b).
So I ran the following code to confirm my conjecture.
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;
But this works!
What??
But I just decided to get this.
&'a mut *&mutx
, not &'a mut *&'b mutx
.
I had no idea why mut x
is unavailable during the lifetime of &mut *&mutx
nor why mut x
is re-available after the lifetime of &mut *&mutx
, but "okay, let's just say so".
But look at this. It's totally out of my mind for a clear and general understanding.
let x: i32 = 1;
let b;
{
let a = &mut x;
let b = &**&a;
} // error!! a should live longer than b!
Wasn't lifetime simply relying on what the real data b
is referring to???
&'a **& &mut x
, not &'a **&'b &'c mut x
.
And now what??
&'a **&'b &mut x
??? (which was my guess).
How should I accept this complicated situation?