Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving mutably borrowed ownership

Tags:

rust

My understanding is that a mutable borrower can move ownership to another mutable borrower. But this move seems to be a bit different from moving a non-pointer variable. Let's see an example. Below p1 gets moved to p2 when compute() is called the first time. But the ownership seems to come back to p1 after compute() returns.

fn compute(p2: &mut Point) {
}

fn reset(p1: &mut Point) {
    compute(p1); //OK
    compute(p1); //OK
}

This is different from how a regular variable is moved.

fn compute(p2:  Point) {
}

fn reset(p1: Point) {
    compute(p1); //OK
    compute(p1); //Compile error
}

Now, ownership does not revert back to p1 after the first compute() call returns.

Both behaviors are understandable and desirable for many reasons. But I just wanted to confirm my understanding that the two moves are slightly different in nature. Am I right thinking this way?

like image 856
RajV Avatar asked Sep 29 '22 03:09

RajV


2 Answers

You're correct except that in the first instance, the reference is not being moved, it's simply being reborrowed, which is behavior particular to references. Perhaps this clears it up, as it's not an exception within move semantics, but a different behavior altogether.

like image 129
Jorge Israel Peña Avatar answered Oct 17 '22 20:10

Jorge Israel Peña


The way I understand it is that your first snippet borrows, where as your second transfers ownership.

fn compute(p2:  Point) {
    // compute owns p2
} // owned p2 is freed

fn reset(p1: Point) {
    // reset() owns p1
    compute(p1); //Ownership of p1 is transferred to compute()
    compute(p1); //ERROR: p1 has already been freed
}

Vice...

fn compute(p2:  &Point) {
    // compute is borrowing p2
} // borrowed p2 is given back to owner

fn reset(p1: Point) {
    // reset() owns p1
    compute(&p1); //let compute() borrow p1, then get it back
    compute(&p1); //let compute() re-borrow p1, then give it back
} // owned p1 is freed
like image 28
kbknapp Avatar answered Oct 17 '22 20:10

kbknapp