Move Semantics (Rust)

A move transfers ownership of a value from one variable to another. After a move the original variable is invalidated, so using it is a compile-time error. Moves are how Rust avoids copying heap data.

Rust

By default, assigning or passing a non-Copy value moves it rather than copying it. For a String, only the small stack metadata (pointer, length, capacity) is bitwise-copied; the heap buffer is not duplicated — it now belongs to the new owner. This makes moves cheap.

After a move the compiler treats the old variable as 'moved out', and any later use is rejected. This prevents two variables from thinking they own the same heap allocation, which would otherwise cause a double free when both go out of scope.

If you actually want both variables, either clone (a deep copy via .clone()) or borrow with a reference. The move keyword also appears on closures (move || ...) to force the closure to take ownership of the variables it captures, which is required when passing a closure to another thread.

Examples

Rust

fn main() {
    let v = vec![1, 2, 3];
    let w = v;          // v moved into w
    println!("{:?}", w);
}

Output:

[1, 2, 3]

Learn it in a lesson

See also

Back to the Dictionary