Changes using mutable reference of a field are not reflected after move of the original instance

I was trying to manipulate the field x of the struct Foo by borrowing a mutable reference from its instance foo.

If I try to print the field x using the moved binding y of the instance foo after the move of the original instance, it keeps printing the value that haven't changed.

Simplified example below:

struct Foo {
    x: i32,
}

fn main() {
    let mut foo = Foo { x: 42 };
    let x = &mut foo.x;
    *x = 13;
    let y = foo;
    println!("{}", y.x); // -> 42; expected result: 13
}

Instead, if I print the moved binding y itself, it prints the changed value.

println!("{:?}", y); // -> Foo { x: 13 }

Or, if I print something else like x or foo.x before the move, it prints the thing as expected.

...
    println!("{}", x); // -> 13
    let y = foo;
    println!("{}", y.x); // -> 13
}

Is this an intended behavior?

This looks like a compiler bug!

Your first program prints 42 in Rust 1.45.0-stable, but it prints 13 in 1.46-beta and 1.47-nightly, so it looks like the bug has already been fixed but the fix is not yet released to the stable channel.

1 Like

Are you intentionally duplicating this?
Edit: now I see your real name is the same as the person on the linked Stack Overflow question. It's a real bug, and it should be fixed in 1.45.1 next week.

https://github.com/rust-lang/rust/issues/74739

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.