Rust Tutorial · Ownership and Borrowing · Lesson 9 of 29

Rust Ownership

The three ownership rules, moves, clones, and Copy types: how Rust manages memory without a garbage collector.

Create a free account to save this page, take notes and track your progress. Sign in

The 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 (its memory freed).

Assigning or passing a heap value like String moves ownership; the old variable can't be used any more.

Moves
fn consume(text: String) {
    println!("consumed: {text}");
}   // text is dropped here

fn main() {
    let a = String::from("order-42");
    let b = a;                 // ownership moves to b
    // println!("{a}");        // error: borrow of moved value: `a`
    consume(b);                // moves into the function
    // println!("{b}");        // error: b was moved too
    println!("both a and b are gone; the memory was freed once");
}

Output

consumed: order-42
both a and b are gone; the memory was freed once

Run this on your computer — see “Get Started” for setup.

Clone and Copy

.clone() makes a deep copy explicitly. Simple values stored on the stack (integers, bool, char, tuples of them) implement Copy and are copied instead of moved.

Clone and Copy
fn main() {
    let original = String::from("config");
    let copy = original.clone();      // explicit deep copy
    println!("{original} and {copy}");
    let x = 5;
    let y = x;                        // i32 is Copy: x is still usable
    println!("{x} and {y}");
}

Output

config and config
5 and 5

Run this on your computer — see “Get Started” for setup.

Test yourself

What happens to s1 after let s2 = s1; when s1 is a String?

  1. s1 and s2 share the string
  2. s1 is moved and can no longer be used
  3. s1 is copied
  4. s1 becomes empty but usable
Show answer

Answer: s1 is moved and can no longer be used

Was this page helpful?