In this lesson, you will learn how Rust’s move semantics physically function at the byte level to transfer ownership between variables.
The Physical Reality of a "Move"
When we talk about "moving" a variable in Rust, we aren't performing a complex transformation or re-allocating memory. At the machine level, a move is simply a shallow bitwise copy of the variable's stack data.
Consider a standard object that owns heap memory, like a String. A String on the stack is just a small structure containing three things: a pointer to the heap, a length, and a capacity. When you write let y = x;, Rust performs a memcpy of those three values (the pointer, length, and capacity) from the stack location of x to the stack location of y.
Byte-for-Byte Transfer
After this memcpy, both x and y technically point to the exact same heap memory. However, Rust’s compiler (the "borrow checker") immediately marks the memory location of x as uninitialized.
It’s important to realize that the computer doesn't "erase" the old bits in x. Instead, the compiler simply treats x as if it no longer exists. If you try to read x later, the compiler throws an error because it knows that the bits at that address are no longer logically valid—the ownership has been transferred to y.
let s1 = String::from("Data");
let s2 = s1; // 24 bytes (on 64-bit) copied from s1 to s2 stack slots.
// s1 is now considered "moved from."
// The pointer, len, and capacity in s1's stack space
// are effectively "dead" to the compiler.
Why it Matters
This mechanism is incredibly efficient. Regardless of whether your heap data is one byte or one gigabyte, the "move" operation always costs the same: the fixed size of the stack-allocated header. By shifting the bits and invalidating the source, Rust ensures that only one variable is responsible for the cleanup (the destructor) of the heap data, preventing double-free errors while maintaining high performance.
Key Takeaway: A move is a shallow bitwise copy of stack memory followed by a logical invalidation of the source variable, ensuring memory safety without expensive deep-copying.