Skip to content

Q012. What is physically moved during a Rust move?

Short Answer

Rust does not guarantee one physical implementation for a move. Inline data may be copied to another location, while a heap-owning value usually transfers only its small handle and leaves the allocation in place. Optimization may reuse storage or remove the transfer entirely. Semantically, only ownership and source usability are guaranteed; no deep clone is implied.

Deep Dive

The physical cost depends on the value's representation:

  • moving an inline array or large struct may copy its bytes;
  • moving a String or Vec<T> conceptually transfers its pointer, length, and capacity, not its heap buffer;
  • moving a Box<T> transfers its owning pointer, not the boxed T;
  • moving a file value transfers its userspace handle representation, not the kernel object.

These descriptions are useful mental models, not stable layout guarantees. The compiler is free to keep values in registers, pass them through an ABI-defined location, reuse the source storage, or eliminate the move.

Internal Model

Move analysis happens before final machine storage is chosen. Code generation lowers the remaining observable data transfers to loads, stores, register moves, or argument passing.

The source bytes are normally not zeroed, and no runtime ownership flag is updated. The compiler simply prevents safe Rust from observing the old place as an initialized value after the move.

Example

rust
struct Packet {
    header: [u8; 64],
    payload: Vec<u8>,
}

fn main() {
    let packet = Packet {
        header: [0; 64],
        payload: vec![1, 2, 3],
    };

    let moved = packet;
    println!("{} {}", moved.header.len(), moved.payload.len());
}

Common Mistakes

  • Assuming the heap allocation moves to a new address.
  • Treating the conceptual layout of library types as a stable ABI promise.
  • Inferring runtime cost only from the number of source-level bindings.

Follow-ups

  • When can moving a large inline value be expensive?
  • Why can returning an owned value avoid copying its heap data?
  • How can optimized machine code be inspected?

References

  • The Rust Programming Language
  • Rust Reference
  • rustc-dev-guide