Course contentsShow
← Rust
Lesson 23 of 1,9101. Rust Fundamentals and ToolingFree lesson

Move Semantics in Practice

Trace variable binding and the transfer of ownership to prevent double-free errors.

Move Semantics in Practice

In this lesson, you will learn how Rust’s "move" semantics enforce memory safety by transferring ownership between variables to prevent double-free errors.

The Problem: Double-Free Errors

In languages without automatic memory management, if two variables point to the same location in memory, both might try to "clean up" (free) that memory when they go out of scope. If the first variable frees the memory, the second one will crash the program when it attempts to free it again. This is called a double-free error.

The Solution: Moving Ownership

Rust solves this by ensuring that for any piece of heap-allocated data, there is only one owner at a time. When you assign one variable to another, Rust performs a "move."

Consider this example:

fn main() {
    let s1 = String::from("Hello"); // s1 owns the data on the heap
    let s2 = s1;                   // The ownership moves from s1 to s2

    // println!("{}", s1);         // ERROR: s1 is no longer valid!
    println!("{}", s2);            // Works perfectly
}

When we set s2 = s1, Rust doesn't copy the actual string data on the heap. Instead, it invalidates s1. Because s1 is no longer the owner, Rust knows it shouldn't try to free that memory when s1 goes out of scope. Only s2 is responsible for the cleanup.

Why This Matters

By "moving" the ownership instead of copying it, Rust makes it physically impossible to have two variables pointing to the same memory that both try to manage its lifecycle. The compiler tracks these moves during the compilation process. If you try to use s1 after it has been moved, the compiler will stop you, ensuring you never encounter a memory corruption bug. You don't have to manage the memory manually; Rust enforces the single-owner rule for you automatically.

Key Takeaway: In Rust, assigning a heap-allocated variable to another variable "moves" ownership, invalidating the original variable and ensuring only one owner exists to safely clean up memory.