As a beginner in Rust, I suddenly became curious about the move
semantics in Rust and whether data is copied when ownership is transferred.
#[derive(Debug)]
struct Foo {
name: i32,
age: i32,
}
fn main() {
let foo = Foo { name: 111, age: 1 };
let ptr_foo = std::ptr::addr_of!(foo);
println!("Address of foo: {:p}", ptr_foo);
let bar = foo;
let ptr_bar = std::ptr::addr_of!(bar);
println!("Address of bar: {:p}", ptr_bar);
}
I asked GPT, and it told me:
No Deep Copying: Rust’s move semantics ensure that the data itself is not deep-copied during such operations. Instead, ownership is simply transferred. This is what distinguishes moves from traditional copying in languages like C or C++. In those languages, copying involves duplicating the data in memory, whereas in Rust, ownership moves without creating duplicates.
This statement seemed strange to me, implying something like “there’s a variable foo
, and after a move
, we simply renamed it to bar
, thus avoiding the need to copy its data”. To investigate further, I used the debug functionality in VSCode with a plugin called “Hex Editor” and found that both foo
and bar
corresponded to the same memory addresses (0x7fffffffd7d8
and 0x7fffffffd828
), containing identical data (6F 00 00 00 01 00 00 00
).
Does this indicate that Rust actually performs a copy operation even during a move
, such as copying a struct in this case? Could this behavior vary depending on whether it’s in release mode?