I have a problem with move ownership?

link to playground

I expected error but nothing happened.

It's only work as I expect if wrap y in scope. But it's not about ownership , the error happened because y out of scope. So It is not that I expected

link

The cases you wrote involve some mutable variable like let mut a = 5; whose mutable reference is reassigned to a new mutable reference.

This is easier as a snippet:

let mut a = 5;
let b = &mut a;
let c = b;
println!("{b}") // fails to print.

In this case, b is indeed moved to c because mutable references do not implement Copy like shared references do.

However, they reborrow in certain circumstances:

let mut a = 5i32;
let b = &mut a;
let c:&mut i32 = b;
println!("{c}"); // moving it after `b` should fail.
println!("{b}")

This last case happens also with the function annotation (which acts like a simple assignment.)

So you get like a stack of mutable references. You can use c before the println!("{b}") but not after (which is what "stacked" would mean here.)

This is my current interpretation at least.

1 Like

Understood. let c: = &mut i32b ; made b moving
because why could't not have 2 &mut ref at same time

The way I read it:

fn move_y(y:&mut Vec<i32>)->(){
    y.push(1);
}
fn main() {
        let mut x = Vec::new();
        let y = &mut x; // Borrowed x as mut ref
        y.push(42); // Used the borrow once
        move_y(y); // move_y (new scope) borrows y (x) as mut ref, the same as
        {
            y.push(2);
        }
        y.push(32); // y is still valid mut ref, all other scopes ended
        let z = &mut x; // Can't use y anymore, previous borrow invalidated
        //y.push(33); // Nope
        z.push(13);
        print!("{:?}",x)
}

Playground

1 Like

you are right. my fn move_y didn't change anything

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.