CourseLesson 6 · Ownership and BorrowingSolve

Lesson 06

Ownership and Borrowing

Ownership is the idea the whole of Rust is built on. Take your time with this lesson. Type every program in, compile it, and read every error message the compiler prints. Nothing later in Rust makes sense until this does.

Two Places for Data

A running program keeps its data in two places.

The stack is a pile of values that grows and shrinks as functions are called and return. When a function starts, its variables are put on top of the pile. When the function ends, they are taken off again. The stack is fast, but it has one condition: every value on it must have a size the compiler knows in advance. A number is a good example. An i32 is always 32 bits wide.

The heap is a large area the program asks for memory from while it runs. You use it when the size is not known in advance, or when it changes. Text typed in by the user is a good example: you cannot know how long it will be until it arrives. Asking for heap memory is slower than putting a value on the stack, and the memory stays reserved until somebody gives it back.

Key idea

Every piece of heap memory has to be given back exactly once. Give it back twice and the program corrupts its own memory. Never give it back and the program slowly eats the machine’s memory. Rust does this for you, and gets it right, by giving every value an owner.

The Three Rules of Ownership

The rules

  1. Every value in Rust has one variable that owns it.

  2. A value has one owner at a time. Never two.

  3. When the owner goes out of scope, the value is dropped and its memory is given back.

The compiler checks these three rules while it compiles. They cost nothing while the program runs. There is no background program cleaning up memory as your code runs, which is how other languages solve the same problem.

Scope and Drop

The scope of a variable is the region of code where it can be used. A variable starts at the let that creates it and ends at the closing brace } of the block it was created in.

fn main() {
    println!("before the block");

    {
        let message = String::from("inside");
        println!("{message}");
    }

    println!("after the block");
}
before the block
inside
after the block

The inner braces make a block. message is created inside it, so it can only be used inside it. At the closing brace Rust drops the value: it gives the memory the text was stored in back to the system. You do not write that line. Rust puts it there.

Use the variable after the block and the program does not compile.

fn main() {
    {
        let message = String::from("inside");
    }

    println!("{message}");
}
error[E0425]: cannot find value `message` in this scope
 --> i.rs:6:16
  |
6 |     println!("{message}");
  |                ^^^^^^^
  |
help: the binding `message` is available in a different scope
      in the same function
 --> i.rs:3:13
  |
3 |         let message = String::from("inside");
  |             ^^^^^^^

Numbers Are Copied

Start with a value that lives only on the stack.

fn main() {
    let x = 5;
    let y = x;

    println!("x = {x}, y = {y}");
}
x = 5, y = 5

Both variables work. let y = x put a second 5 on the stack. An i32 is 32 bits wide and always will be, so copying it means copying 32 bits. That is cheap, and afterwards the two variables have nothing to do with each other. There is no heap memory here, so there is nothing for two owners to fight over.

A String in Memory

String is different. It holds text that can grow, so the text itself sits on the heap. What sits on the stack is three fields: a pointer holding the address of the text, the length in bytes, and the capacity, which is how much heap memory has been reserved.

The three stack fields of a String, with the pointer pointing at the five bytes of hello on the heap

The pointer is an address. It says where the text starts. The text is five bytes long, and five bytes have been reserved for it, so the length and the capacity are both 5.

Assigning a String Moves It

Now do to a String what worked with a number.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1;

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

let s2 = s1 copied the three stack fields into s2. It did not copy the text on the heap. So both variables now hold the same address.

The fields copied from s1 into s2, s1 crossed out, and only s2 pointing at the text on the heap

Two owners of one piece of heap memory breaks rule three. Both variables would go out of scope at the end of main, and both would give the same memory back. Giving the same memory back twice is a serious bug, and it is one of the hardest kinds of bug to find.

Rust does not copy the text to avoid this, because the text could be a megabyte long and copying it would be slow. It does not allow two owners either. Instead it makes s1 invalid the moment s2 takes over. This is called a move. The value moved from s1 into s2, and only s2 will drop it.

Key idea

Assignment in Rust moves the value. The old variable stops working. It is not a copy, and it is not a shared handle to the same data: it is a change of owner, checked while the program is compiled.

Making a Real Copy with clone

When you do want a second, independent copy of the text, ask for one.

fn main() {
    let s1 = String::from("hello");
    let s2 = s1.clone();

    println!("s1 = {s1}");
    println!("s2 = {s2}");
}
s1 = hello
s2 = hello

clone reserves a second piece of heap memory and copies the text into it. Now there are two owners of two separate values, which breaks no rule. Both variables work.

clone costs real time and real memory. That is why Rust makes you write it. When you see clone in a program, you know exactly where the cost is.

Types That Are Copied

Some types are copied on assignment instead of moved, the way i32 was. A type is copied when it has a fixed size and lives entirely on the stack, so there is no heap memory for two owners to share.

  • All the whole number types, such as i32 and u8.

  • The floating point types f32 and f64.

  • bool, which is true or false.

  • char, one character.

  • A tuple, but only when every value inside it is itself copied. (i32, i32) is copied. (i32, String) is moved.

Everything that owns heap memory is moved. String is the example you will meet first.

Passing a Value to a Function

Passing a value to a function is an assignment. The same rules apply.

fn print_length(text: String) {
    println!("{} characters", text.len());
}

fn main() {
    let name = String::from("Rustacean");

    print_length(name);
    println!("name is {name}");
}
error[E0382]: borrow of moved value: `name`
 --> e.rs:9:24
  |
6 |     let name = String::from("Rustacean");
  |         ---- move occurs because `name` has type `String`,
  |              which does not implement the `Copy` trait
8 |     print_length(name);
  |                  ---- value moved here
9 |     println!("name is {name}");
  |                        ^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function
      `print_length` to borrow instead if owning the value
      isn't necessary
 --> e.rs:1:23
  |
1 | fn print_length(text: String) {
  |    ------------       ^^^^^^ this parameter takes
  |                              ownership of the value

The value moved into the parameter text. print_length now owns it. At the closing brace of print_length the value is dropped, and the text is gone before main reaches its next line.

A number behaves differently, because a number is copied.

fn double(n: i32) -> i32 {
    n * 2
}

fn main() {
    let count = 21;

    println!("double is {}", double(count));
    println!("count is still {count}");
}
double is 42
count is still 21

Giving Ownership Back

A function can give ownership back by returning the value.

fn print_length(text: String) -> String {
    println!("{} characters", text.len());
    text
}

fn main() {
    let name = String::from("Rustacean");

    let name_back = print_length(name);
    println!("name is {name_back}");
}
9 characters
name is Rustacean

The last line of print_length is text with no semicolon. A block whose last line has no semicolon gives that value back as the result of the function. So the ownership moves into the function and then straight back out into name_back.

This works, but it is tiring to write. Every function that only wants to read a value has to hand it back afterwards, and the caller has to catch it.

Borrowing a Value

Returning the value works, but there is a shorter way. You can lend the value to the function and keep the ownership yourself. This is called borrowing, and you write it with an ampersand &.

fn print_length(text: &String) {
    println!("{} characters", text.len());
}

fn main() {
    let name = String::from("Rustacean");

    print_length(&name);
    println!("name is {name}");
}
9 characters
name is Rustacean

Two things changed. The parameter type is &String instead of String, and the call passes &name instead of name.

&name is a reference. A reference holds the address of the value. It does not own the value, so nothing is dropped when print_length ends. Only the reference goes out of scope. main still owns the text, and the line after the call still works.

A reference called text pointing at name, which owns the nine bytes of Rustacean on the heap

Key idea

& lends a value. The owner does not change, and the value is not dropped when the reference goes out of scope.

Changing a Borrowed Value

A plain & reference can only read. To let a function change the value, write &mut in both places, and declare the variable mut.

fn add_mark(text: &mut String) {
    text.push('!');
}

fn main() {
    let mut greeting = String::from("hello");

    add_mark(&mut greeting);
    println!("{greeting}");
}
hello!

push adds one character to the end of the text. The change happens to the value main owns, because add_mark was given its address, not a copy.

Leave out the mut on the let line and the program stops compiling.

error[E0596]: cannot borrow `greeting` as mutable, as it
              is not declared as mutable
 --> b3.rs:8:14
  |
8 |     add_mark(&mut greeting);
  |              ^^^^^^^^^^^^^ cannot borrow as mutable
  |
help: consider changing this to be mutable
  |
6 |     let mut greeting = String::from("hello");
  |         +++

You cannot lend out the right to change a value you did not mark as changeable yourself.

The Rules of Borrowing

The rules

At any one point in the code, a value may have either

  1. any number of & references that only read, or

  2. exactly one &mut reference that can change it.

Never both at once, and never two &mut references at once.

Many readers are fine.

fn main() {
    let greeting = String::from("hello");

    let a = &greeting;
    let b = &greeting;

    println!("{a} and {b} and {greeting}");
}
hello and hello and hello

A reader and a writer at the same time is not.

fn main() {
    let mut greeting = String::from("hello");

    let first = &greeting;
    let second = &mut greeting;

    println!("{first} and {second}");
}
error[E0502]: cannot borrow `greeting` as mutable because
              it is also borrowed as immutable
 --> b4.rs:5:18
  |
4 |     let first = &greeting;
  |                 --------- immutable borrow occurs here
5 |     let second = &mut greeting;
  |                  ^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 |     println!("{first} and {second}");
  |                ----- immutable borrow later used here

Two writers are not allowed either. Change &greeting to &mut greeting in the program above and the compiler prints a different error.

error[E0499]: cannot borrow `greeting` as mutable more
              than once at a time

The reason is the same in both cases. If one part of the code is reading the text while another part is changing it, the reader can be left looking at memory that has just been given back. Other languages let you write this and find out when the program crashes. Rust refuses to compile it.

A borrow ends after the last line that uses it. So this compiles.

fn main() {
    let mut greeting = String::from("hello");

    let first = &greeting;
    println!("{first}");

    let second = &mut greeting;
    second.push('!');
    println!("{second}");
}
hello
hello!

first is used for the last time on the println! line above second. The borrow is over from there, so the &mut reference is allowed.

Common Mistakes

Using a Variable After It Was Assigned to Another One

The first variable is dead from the assignment onwards.

fn main() {
    let first = String::from("ferris");
    let second = first;

    println!("{first} and {second}");
}
error[E0382]: borrow of moved value: `first`
 --> f.rs:5:16
  |
3 |     let second = first;
  |                  ----- value moved here
5 |     println!("{first} and {second}");
  |                ^^^^^ value borrowed here after move

Read the error message. It names the line the value moved on, and the line that used it afterwards. Print only second, or write let second = first.clone(); if you really need both.

Reaching for clone at the First Error

clone always compiles, and it is sometimes right. But it copies the data every time you call it.

fn shout(text: String) {
    println!("{}", text.to_uppercase());
}

fn main() {
    let name = String::from("ferris");

    shout(name.clone());
    shout(name.clone());
    println!("{name}");
}
FERRIS
FERRIS
ferris

This program is correct, and it copies the text twice for no reason. Ask first whether the value really needs two owners. Here it does not, because shout only reads the text. Lend it instead.

fn shout(text: &String) {
    println!("{}", text.to_uppercase());
}

fn main() {
    let name = String::from("ferris");

    shout(&name);
    shout(&name);
    println!("{name}");
}
FERRIS
FERRIS
ferris

The output is the same and nothing is copied. name owns the text the whole time.

Expecting a Function to Leave Its Argument Behind

Passing a String to a function hands the function the value.

fn store(text: String) {
    println!("stored {text}");
}

fn main() {
    let label = String::from("box");

    store(label);
    println!("{label}");
}
error[E0382]: borrow of moved value: `label`
 --> k.rs:9:16
  |
8 |     store(label);
  |           ----- value moved here
9 |     println!("{label}");
  |                ^^^^^ value borrowed here after move

The value is gone unless the function gives it back. One fix is to give store the return type -> String, end it with text, and catch the result in main. But store only reads the text, so the shorter fix is to lend it.

fn store(text: &String) {
    println!("stored {text}");
}

fn main() {
    let label = String::from("box");

    store(&label);
    println!("{label}");
}
stored box
box

Ask for ownership only when the function has to keep the value or change who owns it.

Forgetting the Ampersand at the Call

The function type and the call have to agree. Write & in both, or in neither.

fn print_length(text: &String) {
    println!("{} characters", text.len());
}

fn main() {
    let name = String::from("Rustacean");

    print_length(name);
}
error[E0308]: mismatched types
 --> d1.rs:8:18
  |
8 |     print_length(name);
  |     ------------ ^^^^ expected `&String`, found `String`
  |
help: consider borrowing here
  |
8 |     print_length(&name);
  |                  +

The same error appears the other way round when the function asks for &mut String and the call passes &name. The message then says types differ in mutability. Add the mut to the call as well.

Changing a Value While a Reference to It Is Alive

The rules of borrowing apply to the owner too, not only to other references.

fn main() {
    let mut greeting = String::from("hello");

    let first = &greeting;
    greeting.push('!');

    println!("{first}");
}
error[E0502]: cannot borrow `greeting` as mutable because
              it is also borrowed as immutable
 --> d2.rs:5:5
  |
4 |     let first = &greeting;
  |                 --------- immutable borrow occurs here
5 |     greeting.push('!');
  |     ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 |     println!("{first}");
  |                ----- immutable borrow later used here

push needs to change the text, so it needs a &mut borrow, and first is still in use on the last line. Move the println! above the push and the program compiles, because the borrow is then over before the change.

Returning a Reference to a Value the Function Owns

A function cannot lend out a value that it drops itself.

fn make_greeting() -> &String {
    let text = String::from("hello");
    &text
}

fn main() {
    println!("{}", make_greeting());
}
error[E0106]: missing lifetime specifier
 --> d3.rs:1:23
  |
1 | fn make_greeting() -> &String {
  |                       ^ expected named lifetime parameter
  |
help: instead, you are more likely to want to return an
      owned value
  |
1 - fn make_greeting() -> &String {
1 + fn make_greeting() -> String {
  |

text is dropped at the closing brace of make_greeting, so the returned reference would point at memory that has already been given back. Do what the compiler suggests. Return the String itself and give the ownership away.

fn make_greeting() -> String {
    let text = String::from("hello");
    text
}

fn main() {
    println!("{}", make_greeting());
}
hello

Believing a Number Behaves Like a String

Numbers are copied. Nothing moves, and both variables keep working.

fn main() {
    let total = 10;
    let copy = total;

    println!("{total} and {copy}");
}
10 and 10

Swap 10 for String::from("10") and the same program stops compiling. The type decides whether a value is moved or copied.

Using a Value After Its Block Has Closed

A variable ends at the closing brace of the block it was created in.

fn main() {
    {
        let inside = String::from("hello");
        println!("{inside}");
    }

    println!("{inside}");
}
error[E0425]: cannot find value `inside` in this scope
 --> i.rs:7:16
  |
7 |     println!("{inside}");
  |                ^^^^^^
  |
help: the binding `inside` is available in a different
      scope in the same function

This is a different error from the move errors above. The value was dropped at the closing brace, so the name does not exist any more. Declare the variable outside the block if you need it after the block.

Check what stuck

The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →