What difference between type infer and manual assign type?

let x: &mut i32 = &mut 5;
let y = &mut 7;

println!("x: {}, y: {}", x, y);

let x_pin = Pin::new(x);
let y_pin: Pin<&mut i32> = Pin::new(y);

mem::swap(x_pin.get_mut(), y_pin.get_mut());

println!("x: {}, y: {}", x, y);

got following error:
error[E0382]: borrow of moved value: x
--> 16_pin.rs:37:27
|
24 | let x: &mut i32 = &mut 5;
| - move occurs because x has type &mut i32, which does not implement the Copy trait
...
30 | let x_pin = Pin::new(x);
| - value moved here
...
37 | println!("x: {}, y: {}", x, y);
| ^ value borrowed here after move

My question is why 'y' can access but 'x' cannot?

Please post complete examples including all imports so that we don't have to reconstruct all of your imports manually.

As for why one of them fails, it's because mutable references are automatically reborrowed instead of being moved when the target type is known to be a mutable reference without the compiler having to do any type inference.

Unrelated, but the reason you can swap the values is that i32 is Unpin, so pinning them doesn't do 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.