Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 24 - Borrowing: the two rules

A hand holding a book on a short string that stays tied to its owner

Announcements




The one-character fix

We saw this bug before:

fn main() {
    let names = vec![String::from("Alice"), String::from("Bob")];
    let first = names[0];     
    println!("{}", first);
}

What might be a one-character fix?

&names[0] because it does not take the String out of the vector. It only asks to look at it.

The one-owner rule is not broken, because no second owner was created.

This is using references for borrowing, and it is our focus for today and Friday.

Learning Objectives

By the end of today, you should be able to:

  • Explain what a borrow is, and why &names[0] compiles when names[0] doesn't
  • Draw a reference into a Vec, and say what push can do to it
  • State the two borrowing rules, and say what bugs each one prevents
  • Predict whether a program compiles by tracking each borrow from where it's made to its last use
  • Read a borrow-checker error and say which line keeps the borrow alive
  • Draw a struct that owns a String, and an Option or Result, on the stack and heap

Our three kinds of pointers

A pointer is an address. We've now met all three kinds Rust has:

  • Raw pointers: an address and nothing else. Unchecked, so they often need unsafe
  • Owning pointers: Box, Vec, String. The address plus the job of freeing what's at the other end
  • References: &T and &mut T. The address, but no ownership, and the compiler has restrictions for when these are okay

Borrowing is the verb: making a reference is borrowing, and the owner is lending. L ike borrowing a book: your friend still owns it, you read it while you have it, you give it back, and they can use it afterward.

Today we go over the rules for when the compiler lets you borrow or not.

Why Rust has strict rules on borrowing

Here is the bug the rules exist to prevent. Remember what push does when the vector is full:

let mut data = vec![1, 2, 3, 4, 5];   // cap 5, full
let slice = &data[1..3];              // points into the heap, at the 2
data.push(6);                         // no room: allocate bigger, copy, free the old
println!("{:?}", slice);              // slice still points at the old block
Before push:                              After push:

Stack:               Heap:               Stack:               Heap:
┌────────────────┐   ┌───┬───┬───┬───┬───┐   ┌────────────────┐   ┌╌╌╌┬╌╌╌┬╌╌╌┬╌╌╌┬╌╌╌┐
│ data ──────────┼──▶│ 1 │ 2 │ 3 │ 4 │ 5 │   │ data ──────────┼─┐ ╎ 1 ╎ 2 ╎ 3 ╎ 4 ╎ 5 ╎ freed
│ slice ─────────┼──────▶│   │           │   │ slice ─────────┼─┼────▶╎   ╎           ╎
└────────────────┘   └───┴───┴───┴───┴───┘   └────────────────┘ │ └╌╌╌┴╌╌╌┴╌╌╌┴╌╌╌┴╌╌╌┘
                                                                │ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
                                                                └▶│ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │   │   │   │   │
                                                                  └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘

slice is now the C lecture's bug 2, use-after-free, and the program would print whatever landed in the old block.

A reader was looking at the data, a writer moved it, and the reader never found out. That is what the rules have to prevent.

The two borrowing rules

  • Rule 1. At any moment, you can have either any number of & references or exactly one &mut reference. Never both
  • Rule 2. A reference must never outlive what it points at

Rule 1 is the trickier one! There's a lot of nuance, and we'll go over it.

Rule 2 leads to the idea of "lifetimes", which we start today and finish on Friday.

Each rule is one of the C bugs, turned into a compiler error:

RuleBug it preventsHow
1Use-after-free through reallocation; data racesNobody can change the data while someone else is looking at it
2Dangling pointersA reference cannot survive without its data

Remember Rule 1 as "many readers or one writer".

Rule 1 in three programs

Many readers:

fn main() {
    let greeting = String::from("hello");
    let r1 = &greeting;
    let r2 = &greeting;
    let r3 = &greeting[..2];
    println!("{} {} {}", r1, r2, r3);  // all read-only, all fine
}

One writer:

fn main() {
    let mut greeting = String::from("hello");
    let w = &mut greeting;
    w.push_str(" world");
    println!("{}", w);   // the only reference, fine
}

A reader and a writer:

fn main() {
    let mut greeting = String::from("hello");
    let r = &greeting;       // reader
    let w = &mut greeting;   // writer, while the reader is still in use
    println!("{} {}", r, w);  // error
}

The tricky part: the original name counts too!

Changing a value through its own name is a mutable borrow.

fn main() {
    let mut x = 10;
    let y = &x;           // reader
    x = 20;               // error: this is a write, while y is still reading
    println!("{}", y);
}
error[E0506]: cannot assign to `x` because it is borrowed

The original variable does not get special privileges. While another reference is alive, nobody is allowed to change the data through any path.

Reorder it and it compiles:

fn main() {
    let mut x = 10;
    let y = &x;
    println!("{}", y);    // last use of y: the borrow ends here

    x = 20;               // fine, nobody is reading
    println!("{}", x);
}

A borrow ends at its last use

At the last line that uses it. The closing brace is usually later.

fn main() {
    let mut n = 10;

    let r = &n;                    // reader starts
    println!("Reading: {}", r);    // reader's last use: borrow over

    let m = &mut n;                // writer starts
    *m += 5;
    println!("After: {}", m);      // writer's last use: borrow over

    let r2 = &n;                   // a new reader
    println!("Again: {}", r2);
}

Readers and writers, one after another, never at the same time. Three borrows of n, zero conflicts, because none of them overlap.

Activity 24, Problem 1: be the borrow checker

See Problem 1 on Activity 24.

Compiles. reader is made on line 4 and last used on line 5, so its borrow is over before writer is made on line 7. A reader, then a writer, never both at once.

Reading the error

The compiler tells you which rule, and marks all three places. Which borrow is the reader, which is the writer, and which line keeps the reader alive?

fn main() {
    let mut text = String::from("Hello");
    let read = &text;
    println!("{}", read);
    let write = &mut text;
    write.push_str(" World");
    println!("{} {}", read, write);
}
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
  |
3 |     let read = &text;
  |                ----- immutable borrow occurs here
5 |     let write = &mut text;
  |                 ^^^^^^^^^ mutable borrow occurs here
7 |     println!("{} {}", read, write);
  |                       ---- immutable borrow later used here

read is the reader, made on line 3. write is the writer, made on line 5. Line 7 keeps the reader alive: it prints read after the writer exists, so the two borrows overlap.

Without line 7, read's last use would be line 4, its borrow would be over before write was made, and the program would compile.

The fix isn't to delete the &mut. It's to finish reading before you start writing.

On the midterm you will get a program like this, an abridged error, and the question "which rule, and how would you fix it." The three markers are the answer.

Rule 2: a reference cannot outlive its data

We talked about the "dangling pointer" issue in the bug lecture.

Here we see how a borrowing rule prevents it in Rust.

fn get_name() -> &str {
    let name = String::from("Alice");   // name owns "Alice" on the heap
    &name[..]                           // hand back a pointer into it...
}                                       // ...and name is dropped. The heap block is freed

fn main() {
    let n = get_name();                 // n points at the freed block
    println!("Hello, {}", n);           // use-after-free, if this ever ran
}

Rust refuses to compile it: there is no value for it to be borrowed from. How does it know?

What a lifetime is

Lifetime: how long a piece of data is valid.

{
    let x = 5;             // ────┐ x's lifetime starts
    let r = &x;            //     │ r borrows x
    println!("{}", r);     //     │
}                          // ────┘ x's lifetime ends, and r must be done by here

The compiler tracks the lifetime of every value, and checks that no reference is used past the end of the lifetime of what it points at. get_name fails because name ends at the closing brace, and the returned reference would be used after it.

Most of the time Rust works all of this out by itself. Friday: the cases where it asks you to spell it out.

Activity 24, Problem 2: rule 2 on paper

See Problem 2 on Activity 24.

Does not compile, rule 2. inner lives from line 4 to the closing brace on line 7. outer's borrow runs from line 5 to line 8, past the end of inner. The error says so in three places: inner declared here, dropped here while still borrowed, and borrow later used here.

Let's review: References into a collection

Earlier we saw that numbers[0] copies the value out, because i32 is Copy.

&numbers[0] is different: it points into the heap, at the element itself.

For a Vec<String>, you have to use references (or cloning) - you can't do let name = names[0].

fn main() {
    let names = vec![String::from("Alice"), String::from("Bob")];

    // let name = names[0];           // ERROR: cannot move out of index
    let name_ref = &names[0];         // borrow the element
    let name_clone = names[0].clone(); // or copy it, at a cost

    println!("Referenced name: {}", name_ref);
    println!("Cloned name: {}", name_clone);
}
Stack:                              Heap:
┌──────────────────────┐                   Vec buffer
│ main()               │           ┌─────────────────┐
│ ├ names: Vec<String> │      ┌───▶│ String "Alice"  │     ┌─────┬─────┬─────┬─────┬─────┐
│ │  ├ ptr ────────────┼──────┼───▶│ ├ ptr ──────────┼────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │  ├ len: 2          │      │    │ ├ len: 5        │     └─────┴─────┴─────┴─────┴─────┘
│ │  └ cap: 2          │      │    │ └ cap: 5        │
│ ├ name_ref: &String ─┼──────┘    ├─────────────────┤
│ │   (to [0])         │           │ String "Bob"    │     ┌─────┬─────┬─────┐
│ └ name_clone:        │           │ ├ ptr ──────────┼────▶│ 'B' │ 'o' │ 'b' │
│     String           │           │ ├ len: 3        │     └─────┴─────┴─────┘
│     ├ ptr ───────────┼───┐       │ └ cap: 3        │
│     ├ len: 5         │   │       └─────────────────┘
│     └ cap: 5         │   │       ┌─────┬─────┬─────┬─────┬─────┐
└──────────────────────┘   └──────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │  (the clone)
                                   └─────┴─────┴─────┴─────┴─────┘

vec[i] tries to copy or move the value out. For a type that is not Copy, write &vec[i] to borrow it.

A struct that owns a String

struct Player {
    name: String,
    score: u32,
}

fn main() {
    let p = Player { name: String::from("Alice"), score: 10 };

    let whole = &p.name;        // at the handle, inside p
    let start = &p.name[..3];   // into the heap, at the text

    println!("{} {} {}", whole, start, p.score);
}
Stack:                                     Heap:
┌─────────────────────────────┐
│ main()                      │
│ ├ p: Player                 │
│ │  ├ name: String           │◀──┐       ┌─────┬─────┬─────┬─────┬─────┐
│ │  │  ├ ptr ────────────────┼───┼──────▶│ 'A' │ 'l' │ 'i' │ 'c' │ 'e' │
│ │  │  ├ len: 5              │   │       └─────┴─────┴─────┴─────┴─────┘
│ │  │  └ cap: 5              │   │         ▲
│ │  └ score: u32 = 10        │   │         │
│ ├ whole: &String ───────────┼───┘         │
│ └ start: &str               │             │
│     ├ ptr ──────────────────┼─────────────┘
│     └ len: 3                │
└─────────────────────────────┘

A struct's fields sit inline in the frame, so p is a handle and a number, side by side. whole points at the handle, start points past it into the text.

Both are borrows of p.name, and the rules apply to a field exactly as they do to a variable.

Option and Result in memory

While structs have fixed fields, enums have variants.

An enum has as its value it's particular variant, and any data included in that variant.

fn main() {
    let a: Option<i32> = None;
    let b: Option<i32> = Some(3);
    let c: Result<i32, String> = Err(String::from("bad input"));

    let names = vec![String::from("Al"), String::from("Bo")];
    let d: Option<&String> = names.first();

    println!("{:?} {:?} {:?} {:?}", a, b, c, d);
}
Stack:                                    Heap:
┌────────────────────────────┐
│ main()                     │
│ ├ a: Option<i32> = None    │
│ ├ b: Option<i32> = Some(3) │
│ ├ c: Result<i32, String>   │
│ │    = Err(String)         │          ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│ │      ├ ptr ──────────────┼─────────▶│ 'b' │ 'a' │ 'd' │ ' ' │ 'i' │ 'n' │ 'p' │ 'u' │ 't' │
│ │      ├ len: 9            │          └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
│ │      └ cap: 9            │
│ ├ names: Vec<String>       │          Vec buffer
│ │    ├ ptr ────────────────┼─────────▶┌──────────────┐
│ │    ├ len: 2              │          │ String "Al"  │     ┌─────┬─────┐
│ │    └ cap: 2              │     ┌───▶│ ├ ptr ───────┼────▶│ 'A' │ 'l' │
│ └ d: Option<&String>       │     │    │ ├ len: 2     │     └─────┴─────┘
│      = Some(&String) ──────┼─────┘    │ └ cap: 2     │
└────────────────────────────┘          ├──────────────┤
                                        │ String "Bo"  │     ┌─────┬─────┐
                                        │ ├ ptr ───────┼────▶│ 'B' │ 'o' │
                                        │ ├ len: 2     │     └─────┴─────┘
                                        │ └ cap: 2     │
                                        └──────────────┘

On a diagram, write the variant and its value where the variable is, just like basic copy types If the value has a pointer, draw the pointer and the data on the heap.

Take-aways

  • A borrow is a reference with no ownership. Making one is borrowing, and the owner is lending
  • Rule 1: any number of &, or exactly one &mut, never both at once. The owner's own name counts as a writer
  • Rule 2: a reference never outlives what it points at
  • A borrow ends at its last use, which is usually before the closing brace
  • A &mut into part of a vector is a &mut to the whole vector, because push can move everything
  • The error marks three places: where the reader was made, where the writer was made, and the later use that keeps the reader alive
  • On a diagram, a struct's fields sit inline, and an enum is its variant and value where the variable is

Friday: what the rules mean for the functions you write, and when you have to spell out a lifetime.

Activity 24

See Activity 24. Be the borrow checker: nine programs, bracket every borrow, and decide what the compiler says. Problems 1 and 2 are done, so start at Problem 3.