Lesson 6

Ownership

Understand Rust's most unique feature: ownership, move semantics, and the Copy trait.

The Big Idea

Ownership is Rust's secret weapon -- it's how Rust guarantees memory safety without a garbage collector. There are three rules:

  1. Each value has one owner (a variable).
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value is dropped (freed).

Move Semantics

When you assign a heap-allocated value (like a String) to another variable, ownership moves. The original variable becomes invalid -- you can't use it anymore. This prevents double-free bugs.

let s1 = String::from("hello");
let s2 = s1;  // s1 is MOVED to s2
// println!("{}", s1);  // ERROR: s1 is no longer valid

Fixing "borrow of moved value" (E0382)

Using s1 after the move is the most common error new Rust programmers see. The compiler points at all three places involved:

error[E0382]: borrow of moved value: `s1`
  |     let s1 = String::from("hello");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
  |     let s2 = s1;
  |              -- value moved here
  |     println!("{}", s1);
  |                    ^^ value borrowed here after move

There are three ways to fix it, in the order you should usually try them:

  1. Borrow instead of moving. let s2 = &s1; gives s2 a reference, and s1 stays the owner. This is the next lesson, References & Borrowing.
  2. Use the value before you move it. If s1 is only needed for a moment, print it first and move it afterwards.
  3. Clone it. let s2 = s1.clone(); copies the heap data, so both variables own their own string. It is what the compiler suggests, but it costs an allocation, so prefer borrowing when you only need to read.

The same error appears when you pass a String to a function that takes ownership and then use it again. The fixes are the same: make the function take &str, or return the value back, as give_and_take does below.

Copy Types

Simple types like integers, floats, and booleans implement the Copy trait. They're copied instead of moved, so both variables remain valid. Stack-only data is cheap to copy.

Run the code below. Then try uncommenting the marked line to see what the compiler says.

Try it

fn main() {
    // --- Integers are COPIED ---
    let a = 42;
    let b = a;  // a is copied, both are valid
    println!("a = {}, b = {}", a, b);

    // --- Strings are MOVED ---
    let s1 = String::from("hello");
    let s2 = s1;  // s1 is moved to s2
    println!("s2 = {}", s2);

    // Uncomment the next line to see a compile error:
    // println!("s1 = {}", s1);  // ERROR: value borrowed after move

    // --- Clone: explicit deep copy ---
    let s3 = String::from("world");
    let s4 = s3.clone();  // deep copy, both are valid
    println!("s3 = {}, s4 = {}", s3, s4);

    // --- Ownership and functions ---
    let name = String::from("Rust");
    take_ownership(name);
    // name is no longer valid here -- it was moved into the function

    let x = 10;
    make_copy(x);
    println!("x is still valid: {}", x);  // works because i32 is Copy

    // --- Getting ownership back ---
    let greeting = String::from("hi there");
    let greeting = give_and_take(greeting);
    println!("Got it back: {}", greeting);
}

fn take_ownership(s: String) {
    println!("I own: {}", s);
}  // s is dropped here

fn make_copy(n: i32) {
    println!("I got a copy: {}", n);
}

fn give_and_take(s: String) -> String {
    println!("Passing through: {}", s);
    s  // return ownership back to caller
}

Challenge

Try uncommenting the line that causes a compile error. Read the error message carefully -- Rust's compiler gives excellent explanations.

Previous: Control Flow

Next: References & Borrowing