Why when we move a variable in an other, these are not the same pointer?


Why when we move a variable in an other, these are not the same pointer ?
We can notice that the struct A do not implement Copy trait.
I don't understand this behavior because the data can not to be reach by the identifier (a) anymore.


struct A();

impl fmt::Pointer for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ptr = self as *const Self;
        fmt::Pointer::fmt(&ptr, f)

fn main() {
    let a = A();
    println!("a : {:p}",a);
    let b = a;
    println!("b : {:p}",b);

Output :

a : 0x7ffe05f10df8
b : 0x7ffe05f10e48
1 Like

This happens because debug mode doesn't apply any optimization, if you build it in release mode you'll see it has the same address. Playground. However don't rely on this fact, this isn't guaranteed and may be a pure coincidence.


If you don't want the address to change, then you have to use references / pointers instead of moving the data.

As was mentioned by @SkiFire13, while release mode will usually elide the copy during optimization, Rust does not make any promises about it. Relying on this optimization in unsafe code will result in undefined behavior.


There is some confusion over what move and/or copy means. Or at least there was for me.

When I see:

    let a = A();
    let b = a;

I would have naturally expected that makes a copy of a in b and they are both subsequently available for use. Of course that copy is likely performed by an instruction called MOV, at least on x86 (And of course the x86 MOV is a misnomer as it actually makes a copy).

As noted above, in Rust that sequence may or may not result in the bit pattern that constitutes a being duplicated in memory to make 'b`, depending on optimization level, phase of the moon etc.

So what is actually being moved then? Clearly not the bit pattern that is the value of a. As any old school assembler/C programmer would expect.

No, in Rust it is the ownership of the value that is being moved from one name to another.

It's rather like the way banks move gold bullion from one account to another. Those gold bricks don't actually move anywhere, they stay locked up in their vault. But the bank moves the ownership from account to account.


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.