Rust Playbook

Course › Week 1 · Basics and ownership › Day 3 · lesson 3 of 42 · 10 min reading + 60–90 min practice

Ownership: who owns a value

Every value has exactly one owner, assigning a String moves it, and the old name stops working.

ownershipmoveStringCloneCopydrop

On this page
  1. 1. A String lives on the heap
  2. 2. The three rules
  3. 3. Scope: where the owner lives
  4. 4. Assigning a String moves it
  5. 5. Passing a String to a function moves it too
  6. 6. A function can give ownership back
  7. 7. clone: an explicit copy
  8. 8. Numbers are copied, not moved
  9. Coming from PHP
  10. Practice
  11. Remember

PHP frees memory for you while the program runs: every value keeps a count of how many variables point to it, and when the count reaches zero, PHP frees it. That bookkeeping runs all the time.

Rust has no such bookkeeping. Instead, the compiler works out, before the program runs, the exact line where each value is freed. It can only do that because of three rules called ownership. Today is only about those rules and what they mean for assigning a value and passing it to a function. Tomorrow is about lending a value without giving it away.

Go slowly today. Use the Brown edition of chapter 4 for its diagrams.

1. A String lives on the heap

A number like 3 has a fixed size, so Rust keeps it right inside the variable. A String can grow, so its text lives in a separate area of memory called the heap, and the variable holds a pointer to it, plus its length and capacity.

src/main.rs
fn main() {
    let mut name = String::from("Nyhavn"); // text on the heap, owned by name
    name.push_str(" flat"); // the text grows: the heap part is resized

    println!("{name}");
}
$ cargo run
Nyhavn flat

"Nyhavn" written in quotes is a fixed piece of text built into the program. String::from copies it into a growable String that your code owns. You will meet both kinds of text again tomorrow.

2. The three rules

RuleEach value has one owner. There is only one owner at a time. When the owner goes out of scope, the value is dropped (freed).

Everything else today follows from these three sentences.

3. Scope: where the owner lives

A scope is a pair of braces. A variable lives from its let to the closing brace of the scope it was declared in. At that brace, Rust frees what it owns.

src/main.rsdoes not compile
fn main() {
    {
        let guest = String::from("Lina");
        println!("inside: {guest}");
    } // guest goes out of scope here, and its text is freed

    println!("outside: {guest}");
}
cargo build
error[E0425]: cannot find value `guest` in this scope
 --> src/main.rs:7:25
  |
7 |     println!("outside: {guest}");
  |                         ^^^^^
  |
help: the binding `guest` is available in a different scope in the same function
 --> src/main.rs:3:13
  |
3 |         let guest = String::from("Lina");
  |             ^^^^^

For more information about this error, try `rustc --explain E0425`.
error: could not compile `hello` (bin "hello") due to 1 previous error

This rule is the same in PHP for a function’s variables. What is new is what happens when two variables are involved.

4. Assigning a String moves it

If let s2 = s1; copied only the pointer, two variables would own the same text, and at the closing brace Rust would free it twice: a classic crash in C. Copying the text itself on every assignment would be slow. So Rust does neither: it moves ownership to s2, and s1 can no longer be used.

If Rust copied the pointer

s1s2heap: "Lina"freed twice

Two owners: both would free the same text at the closing brace.

What Rust does: a move

s1 (moved)s2heap: "Lina"one ownerunusable

Ownership moves to s2. s1 still exists as a name, but the compiler refuses any use of it.

src/main.rsdoes not compile
fn main() {
    let s1 = String::from("Lina");
    let s2 = s1;

    println!("{s1} and {s2}");
}
cargo build
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:5:16
  |
2 |     let s1 = String::from("Lina");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;
  |              -- value moved here
4 |
5 |     println!("{s1} and {s2}");
  |                ^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s2 = s1.clone();
  |                ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous error

Read the error top to bottom: where the value was created, where it moved, where you tried to use it after. The help: line already suggests one fix, .clone(), which you will see in section 7.

5. Passing a String to a function moves it too

A function parameter is a new owner. Calling print_guest(guest) moves guest into the function, and when the function ends, the text is freed there.

src/main.rsdoes not compile
fn print_guest(name: String) {
    println!("Guest: {name}");
} // name goes out of scope: the text is freed here

fn main() {
    let guest = String::from("Lina");

    print_guest(guest);
    print_guest(guest);
}
cargo build
error[E0382]: use of moved value: `guest`
 --> src/main.rs:9:17
  |
6 |     let guest = String::from("Lina");
  |         ----- move occurs because `guest` has type `String`, which does not implement the `Copy` trait
7 |
8 |     print_guest(guest);
  |                 ----- value moved here
9 |     print_guest(guest);
  |                 ^^^^^ value used here after move
  |
note: consider changing this parameter type in function `print_guest` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:22
  |
1 | fn print_guest(name: String) {
  |    -----------       ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
8 |     print_guest(guest.clone());
  |                      ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous error

Look at the note: in the error: “consider changing this parameter type in function print_guest to borrow instead”. That is exactly tomorrow’s lesson.

6. A function can give ownership back

Returning a value moves it out to the caller. So one way to keep using a String is to take it in and hand it back:

src/main.rs
fn with_title(mut name: String) -> String {
    name.insert_str(0, "Ms ");
    name
}

fn main() {
    let guest = String::from("Lina");
    let guest = with_title(guest); // moved in, moved back out

    println!("{guest}");
}
$ cargo run
Ms Lina

It works, and for a function that transforms a value it is the right shape. But for a function that only reads a value, handing it back every time would be tiring. Tomorrow’s borrowing solves that.

mut name: String means the function’s own variable is mutable. The caller’s variable did not need to be.

7. clone: an explicit copy

When you really want two independent Strings, ask for a copy with .clone(). It copies the heap text, so it costs time and memory, and that cost is visible in the code.

src/main.rs
fn main() {
    let s1 = String::from("Lina");
    let s2 = s1.clone(); // a second copy of the text on the heap

    println!("{s1} and {s2}");
}
$ cargo run
Lina and Lina

A common beginner habit is to add .clone() wherever the compiler complains. It makes the error go away and hides the design problem. In this course, a .clone() needs a reason you could say out loud.

8. Numbers are copied, not moved

Simple fixed-size values are so cheap to copy that Rust copies them on assignment, and both variables stay usable. These types are called Copy types: all integers, floats, bool, char, and tuples or arrays made only of them.

src/main.rs
fn double(n: u32) -> u32 {
    n * 2
}

fn main() {
    let nights: u32 = 3;
    let copy = nights; // a copy: nights is still usable

    println!("{}", double(nights)); // a copy goes into the function
    println!("{nights} {copy}");
}
$ cargo run
6
3 3

So the rule of thumb: values with a heap part (String, and next week Vec and HashMap) move; plain numbers and booleans copy.

Coming from PHP

PHP has two behaviours, and neither is a move. Arrays and strings behave like copies (PHP only really copies when one side is changed, “copy on write”). Objects are shared: two variables point at the same object, and either can change it.

ownership.php
<?php

$a = ['Lina'];
$b = $a;           // behaves like Rust's clone(): two independent arrays
$b[] = 'Omar';     // $a is still ['Lina']

$x = new ArrayObject(['Lina']);
$y = $x;           // two names, ONE object: like nothing in safe Rust
$y[] = 'Omar';     // $x sees 'Omar' too

The second case, two variables that can both change the same thing, is the source of a whole family of bugs: one part of the code modifies an object another part is still relying on. Safe Rust never allows two owners. Tomorrow you will see the one controlled way it allows two names for one value.

PracticeThe Book ch. 4.1, Rustlings move_semantics 1–3

Read chapter 4.1 in the Brown edition, with its diagrams and quizzes.

In Rustlings: 06_move_semantics, exercises 1 to 3.

Exercise: fix it twice

This program does not compile. Fix it in two different ways: once with clone, once by changing welcome so it hands the String back. Then decide which fix you would keep, and why.

src/main.rsdoes not compile
fn welcome(name: String) {
    println!("Welcome, {name}!");
}

fn main() {
    let guest = String::from("Omar");

    welcome(guest);
    println!("Checked in: {guest}");
}
cargo build
error[E0382]: borrow of moved value: `guest`
 --> src/main.rs:9:28
  |
6 |     let guest = String::from("Omar");
  |         ----- move occurs because `guest` has type `String`, which does not implement the `Copy` trait
7 |
8 |     welcome(guest);
  |             ----- value moved here
9 |     println!("Checked in: {guest}");
  |                            ^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `welcome` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:18
  |
1 | fn welcome(name: String) {
  |    -------       ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
8 |     welcome(guest.clone());
  |                  ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous error
Show the two fixes

With clone: one extra copy of the text, so the function can keep its own.

src/main.rs (fix 1)
fn welcome(name: String) {
    println!("Welcome, {name}!");
}

fn main() {
    let guest = String::from("Omar");

    welcome(guest.clone());
    println!("Checked in: {guest}");
}
$ cargo run
Welcome, Omar!
Checked in: Omar
Show fix 2 and which to keep

Handing it back: no copy, but the function’s signature now says it returns the name, which is odd for a function that only prints.

src/main.rs (fix 2)
fn welcome(name: String) -> String {
    println!("Welcome, {name}!");
    name
}

fn main() {
    let guest = String::from("Omar");

    let guest = welcome(guest);
    println!("Checked in: {guest}");
}
$ cargo run
Welcome, Omar!
Checked in: Omar

Neither is the fix you would ship. welcome only reads the name, so it should borrow it. That is tomorrow’s first program.

Remember

  • One owner per value; assigning or passing a String moves it, and the old name is dead.
  • Numbers and booleans are copied; .clone() is an explicit, visible cost that needs a reason.

Tomorrow: borrowing, how a function can read or change a value without taking ownership of it.