BeginnerLesson 3 of 156 min read

Ownership and Borrowing: The Rules That Replace Garbage Collection

Learn Rust ownership, moves, clone, shared and mutable references, and see the compiler's real messages for use after move and for two mutable borrows.

In this lesson you will

  • State the three ownership rules
  • Move, clone and borrow values
  • Use shared and mutable references
  • Read the borrow checker’s messages

About 28 minutes

Who frees the memory?

Every language must decide who releases a piece of memory when it is no longer needed. C leaves it to the programmer, which causes leaks and use after free. Java and Go use a garbage collector, which costs time and memory at run time. Rust uses a third way: ownership, a small set of rules that the compiler checks, so that memory is released at exactly the right moment with no run-time cost and no possibility of use after free. The rules are three. Each value has one owner. There is only one owner at a time. And when the owner goes out of scope, the value is dropped, which frees its memory.

When you assign a value that owns heap memory, such as a String, to another variable, ownership moves, and the old variable can no longer be used. To make an independent copy, you call clone. To use a value without taking it, you borrow it with a reference: &x is a shared reference, many of which may exist at once, and &mut x is a mutable reference, of which there may be only one, and not at the same time as any shared reference. These rules, “many readers or one writer”, are what prevent data races and iterator invalidation, and the compiler checks them before the program runs. Simple values such as integers are copied automatically, since they live on the stack and have the Copy trait.

Operation Effect
let b = a; (a String) Moves ownership; a is unusable
let b = a.clone(); Deep copy; both usable
fn f(s: &String) Borrows read-only; caller keeps ownership
fn f(s: &mut String) Borrows to modify; only one at a time
let b = a; (an i32) Copies; both usable
fn length(s: &String) -> usize { s.len() }
fn shout(s: &mut String) { s.push_str("!!"); }
fn consume(s: String) -> usize { s.len() }

fn main() {
    let a = String::from("turbine 7");
    let b = a.clone();
    println!("clone: a = {:?}, b = {:?}", a, b);
    let n = length(&a);
    println!("borrowed read-only: length {}, a still usable: {:?}", n, a);
    let mut c = String::from("alarm");
    shout(&mut c);
    println!("mutable borrow changed c to {:?}", c);
    let r1 = &c;
    let r2 = &c;
    println!("two shared references at once: {} and {}", r1, r2);
    let taken = consume(c);
    println!("consume took ownership and returned the length {}", taken);
    let x = 5;
    let y = x;
    println!("integers are copied: x = {}, y = {}", x, y);
    {
        let inner = String::from("scoped");
        println!("inside the block: {}", inner);
    }
    println!("the block ended, inner was dropped automatically");
}
clone: a = "turbine 7", b = "turbine 7"
borrowed read-only: length 9, a still usable: "turbine 7"
mutable borrow changed c to "alarm!!"
two shared references at once: alarm!! and alarm!!
consume took ownership and returned the length 7
integers are copied: x = 5, y = 5
inside the block: scoped
the block ended, inner was dropped automatically
fn main() {
    let a = String::from("turbine");
    let b = a;
    println!("{} {}", a, b);
}
error[E0382]: borrow of moved value: `a`
 --> m.rs:4:23
  |
2 |     let a = String::from("turbine");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 |     let b = a;
  |             - value moved here
4 |     println!("{} {}", a, b);
  |                       ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let b = a.clone();
  |              ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0382`.
fn main() {
    let mut s = String::from("alarm");
    let first = &mut s;
    let second = &mut s;
    first.push('!');
    second.push('?');
    println!("{}", s);
}
error[E0499]: cannot borrow `s` as mutable more than once at a time
 --> m.rs:4:18
  |
3 |     let first = &mut s;
  |                 ------ first mutable borrow occurs here
4 |     let second = &mut s;
  |                  ^^^^^^ second mutable borrow occurs here
5 |     first.push('!');
  |     ----- first borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0499`.
error[E0382]: borrow of moved value: `a`
error[E0499]: cannot borrow `s` as mutable more than once at a time

The clone made an independent copy, so both a and b hold “”turbine 7″”, while the borrowing function read a without taking it: the length is 9 and a is still usable afterwards. The mutable borrow let shout change c to “alarm!!”, and two shared references to the same string existed at the same time without any problem. When c was passed by value to consume, ownership moved into the function, which returned the length 7, and c could not be used again. Integers are copied, so x and y both hold 5, and the inner string was dropped automatically at the closing brace of its block, with no free call and no garbage collector.

The two failing programs show the compiler enforcing the rules. In the first, b = a moved the string, so using a afterwards is error E0382, “borrow of moved value”, and the compiler’s full message points at the move and at the later use and suggests cloning. In the second, taking a second mutable reference while the first is still in use is error E0499, “cannot borrow as mutable more than once at a time”. Both errors are found before the program runs, and they are the two bugs, use after free and data races, that cause most security problems in C and C++ programs. You can read the whole messages with cargo build, and the error codes with rustc –explain.

Check by hand: “turbine 7” has 9 characters, 7 letters, a space and a digit. “alarm” plus “!!” is 7 characters, the length that consume returned. Reading through two shared references is allowed because nobody can change the data while they exist, and a mutable reference must be unique for the same reason.

Do not fight the borrow checker with clone everywhere

Cloning to silence the compiler works, and it can hide a design problem and cost time and memory. First try to borrow, or restructure so that one owner is clear.

Read the whole error message

Rust errors point at the exact lines, label the move or the borrow, and often suggest a fix, such as borrowing instead of moving. They are the best teacher you have.

About this course

Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording. The error messages shown are from the course compiler. Wording changes between versions.

Practice

Write a function that takes a &Vec and returns its sum, and another that takes &mut Vec and doubles every element. Call them in order on one vector. Then try to call both in a way that overlaps, and read the error.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What happens when you assign a String to another variable?

  1. It is copied
  2. Both share it
  3. It is freed
  4. Ownership moves and the old variable is unusable

Use clone for a copy.

How many mutable references to a value may exist at once?

  1. Two
  2. Any number
  3. One
  4. None

And no shared ones at the same time.

When is a value dropped?

  1. Never
  2. When the program ends only
  3. When its owner goes out of scope
  4. When it is cloned

No garbage collector.

Why are integers copied automatically?

  1. They are small strings
  2. They have the Copy trait and live on the stack
  3. They are references
  4. They are macros

Moves apply to values that own resources.

Which error means use of a moved value?

  1. E0499
  2. E0382
  3. E0308
  4. E0425

The compiler also explains it.

Summary

  • Each value has one owner, and it is dropped when the owner leaves scope.
  • Assignment moves; clone copies; Copy types are copied automatically.
  • Many shared references or one mutable reference, never both.
  • The compiler checks all of this before the program runs.

Next lesson

Lesson 4 covers functions, control flow, match and Option.

Questions

Is the borrow checker slow?

No. It runs at compile time. There is no run-time cost for these checks.

Why can I have many shared references but one mutable?

Many readers cannot conflict. A writer together with a reader could, which is how data races and invalidated iterators arise.

How do I share ownership?

With Rc for single-threaded code and Arc for threads, which count the owners. Lesson 14 shows Arc.

Progress is saved in this browser.