Skip to content
LumenaryAcademy
Foundations 60 min

Ownership, borrowing and lifetimes

The three rules that let Rust free memory without a garbage collector, and how to work with the borrow checker instead of against it.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Who frees the memory?

A running program constantly asks for memory: room for a line of text read from a file, a list that keeps growing, a picture being decoded. Sooner or later that memory must be given back, or the program will grow until the machine runs out. Every language has to answer the question: who frees it, and when?

In C, the programmer does, by calling free. Free too late (or never) and the program leaks. Free twice and the allocator's bookkeeping is corrupted. Free too early, while some other part of the program still holds the address, and that part will later read or write memory that now belongs to something else. These use-after-free bugs are among the most exploited security flaws in the world, and they are hard to find because the program often seems to work.

In Java, Python, Go or JavaScript, a garbage collector frees memory once nothing refers to it any more. This removes the whole class of bugs, at the price of a runtime that periodically traces through memory and of less control over when cleanup happens.

Rust's answer is ownership. Every value has exactly one owner, a variable or another value that contains it, and the value is freed at a precise, predictable point: when its owner goes out of scope. Other code may borrow the value for a while, but the compiler proves, before the program runs, that no borrow outlives the value and that nobody changes a value while someone else is reading it. There is no runtime cost, because all the checking is done by the borrow checker during compilation.

This lesson is the one that makes Rust feel different from every language you have used. Take it slowly; everything later builds on it.

IntuitionH

Stack, heap, and what a String really is

A program's memory has two regions that matter here. The stack holds each function's local variables in a block that is pushed when the function is called and popped when it returns. It is very fast, but everything on it must have a size known at compile time and disappears when the function ends. The heap is a large pool from which a program can request blocks of any size at run time and keep them as long as it likes. Somebody has to give heap blocks back.

An i32 or a (f64, f64) lives entirely on the stack. A String does not: its text can grow, so the characters live in a heap block, and the String value itself is a small fixed-size record of three numbers on the stack: a pointer to the heap block, the length in use, and the capacity of the block.

stackheapaptrlen 5cap 5movedbptrlen 5cap 5jambo
After let b = a; with a String: the three-word record on the stack is copied into b, but the heap bytes are not. Ownership of the heap block moves to b, and a can no longer be used, so the block will be freed exactly once, when b goes out of scope.

Now imagine let b = a; for a String. Copying all the heap bytes would be slow and surprising. Copying just the three-word record would leave two variables pointing at the same block, and when both went out of scope the block would be freed twice. Rust does the second, cheaper thing but declares that a is no longer valid: the value has moved to b. Exactly one owner remains, so exactly one free will happen.

Analogy, not a formal construction

Ownership works like a physical book. If you give your copy to a friend, you no longer have it; you can't read it, and you can't give it away again. You can also lend it: either to several people at once who only read it, or to one person at a time who writes notes in the margins, but never both together, and you must not throw it away while it is on loan. Moves are gifts, references are loans, and the borrow checker is a very strict librarian.

DefinitionsH

The ownership rules

Definition— ownership

  1. Each value has exactly one owner.
  2. When the owner goes out of scope, the value is dropped: its destructor runs and its memory (including any heap memory) is freed.
  3. Ownership can be moved to another owner, by assignment, by passing the value to a function, or by returning it. After a move, the old name cannot be used.

Definition— Copy and Clone

Types whose values are just bits with no resources attached (integers, floats, bool, char, shared references, and tuples or arrays of these) implement the Copy trait: assignment copies them and the original stays usable. Other types may implement Clone, which provides an explicit .clone() method that makes an independent deep copy.

rust
fn shout(text: String) -> String {
    text.to_uppercase() + "!"
}

fn main() {
    let greeting = String::from("jambo");
    let loud = shout(greeting); // ownership of the String moves into `shout`
    // println!("{greeting}");  // error[E0382]: borrow of moved value: `greeting`
    println!("{loud}");

    let a = String::from("chai");
    let b = a.clone(); // an explicit, independent copy of the heap data
    println!("{a} and {b}");

    let x = 5;
    let y = x; // i32 is Copy: both remain usable
    println!("{x} and {y}");

    let pair = (String::from("left"), 7);
    let (text, number) = pair; // destructuring moves the String out
    println!("{text} {number}");
}
text
JAMBO!
chai and chai
5 and 5
left 7

If you uncomment the line that prints greeting, here is what the compiler says (abridged slightly at the end):

text
error[E0382]: borrow of moved value: `greeting`
 --> mv.rs:8:16
  |
6 |     let greeting = String::from("jambo");
  |         -------- move occurs because `greeting` has type `String`, which does not implement the `Copy` trait
7 |     let loud = shout(greeting);
  |                      -------- value moved here
8 |     println!("{greeting}");
  |                ^^^^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary

It names the type that caused the move, shows where the move happened and where the stale name was used, and suggests two fixes: make shout borrow its argument, or clone. The first is usually right, and it is the subject of the next section.

Dropping is just as precise as moving. In the program further below, a type that prints a message from its destructor shows the order: values are dropped at the end of the block that owns them, in the reverse order of their declaration, and a value that was moved is dropped by its new owner, once. This determinism is called RAII (resource acquisition is initialisation), a term from C++: files close, locks release and network connections shut at a point you can see in the source, not whenever a collector gets round to it.

DefinitionsH

Borrowing: many readers or one writer

Moving a value into every function that looks at it would be tiresome. Instead, a function can borrow it through a reference.

Definition— references

&value creates a shared reference (type &T): it lets you read the value but not change it, and any number of shared references may exist at once. &mut value creates a mutable reference (type &mut T): it lets you change the value, and while it is in use no other reference to that value may be used. In every case, a reference must never outlive the value it points to.

rust
fn count_vowels(text: &str) -> usize {
    text.chars().filter(|c| "aeiouAEIOU".contains(*c)).count()
}

fn add_surname(name: &mut String, surname: &str) {
    name.push(' ');
    name.push_str(surname);
}

fn main() {
    let mut name = String::from("Ngozi");
    println!("{name} has {} vowels", count_vowels(&name));

    add_surname(&mut name, "Okonjo");
    println!("now {name:?}, {} vowels", count_vowels(&name));

    // Any number of shared borrows at once...
    let r1 = &name;
    let r2 = &name;
    println!("{} {}", r1.len(), r2.len());

    // ...and, once they are no longer used, one mutable borrow.
    let r3 = &mut name;
    r3.make_ascii_uppercase();
    println!("{name}");
}
text
Ngozi has 2 vowels
now "Ngozi Okonjo", 5 vowels
12 12
NGOZI OKONJO

Notice that the caller writes &name and &mut name explicitly: you can see at every call site whether a function might change your data. Notice too that r3 is created while r1 and r2 are still in scope. That is allowed because a borrow lasts only until its last use, not until the end of the block (the compiler's "non-lexical lifetimes"); r1 and r2 are last used in the println! above.

Why forbid reading and writing at the same time, even in a single thread? Here is the classic case:

rust
let mut scores = vec![10, 20, 30];
let first = &scores[0];
scores.push(40);
println!("{first}");
text
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> br.rs:4:5
  |
3 |     let first = &scores[0];
  |                  ------ immutable borrow occurs here
4 |     scores.push(40);
  |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{first}");
  |                ----- immutable borrow later used here

This is not pedantry. A vector keeps its elements in one heap block; if push finds the block full, it allocates a bigger one, copies the elements across and frees the old block. first would then point into freed memory. In C++ this exact bug (iterator or reference invalidation) compiles silently and sometimes works; in Rust it cannot compile. The same rule, applied across threads, is what makes data races impossible in safe Rust (lesson 9).

Worked examplesH

Slices and strings

A slice is a borrowed view of a contiguous run of elements owned by something else. &[T] is a slice of any array or vector; &str is a slice of UTF-8 text. A slice is a pointer plus a length, so it is cheap to pass around. Slices are the reason idiomatic functions take &str rather than &String and &[T] rather than a reference to a vector: one function then accepts owned strings, literals and pieces of strings alike.

rust
fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(i) => &text[..i],
        None => text,
    }
}

fn total(values: &[i32]) -> i32 {
    let mut sum = 0;
    for v in values {
        sum += v;
    }
    sum
}

fn main() {
    let owned = String::from("São Paulo is large");
    let literal: &str = "Kraków is old";
    println!("{} / {}", first_word(&owned), first_word(literal));

    println!("{} bytes, {} chars", owned.len(), owned.chars().count());
    println!("{:?}", &owned[0..4]);

    let readings = [3, 1, 4, 1, 5, 9, 2, 6];
    println!("all: {}, middle four: {}", total(&readings), total(&readings[2..6]));

    let numbers = vec![10, 20, 30];
    println!("a Vec lends a slice too: {}", total(&numbers));
}
text
São / Kraków
19 bytes, 18 chars
"São"
all: 31, middle four: 19
a Vec lends a slice too: 60

&owned is a &String, and Rust automatically converts it to a &str where one is expected (a deref coercion). A string literal is already a &str pointing into the program's own binary, which is why its type is &'static str: it lives for the whole run.

The string example deserves a closer look. "São Paulo is large" has 18 characters but takes 19 bytes, because ã needs two bytes in UTF-8. String lengths and slice ranges are measured in bytes, so &owned[0..4] is "São" (S, then the two bytes of ã, then o). Slicing in the middle of a character is a bug that Rust catches at run time: &owned[0..2] panics with "byte index 2 is not a char boundary; it is inside 'ã' (bytes 1..3)". And owned[0] does not compile at all; the compiler explains that string indices are ranges and suggests .chars().nth() or .bytes().nth(). Text is not an array of characters, and Rust refuses to pretend otherwise; for user-visible "characters" in all scripts, the community crate unicode-segmentation handles grapheme clusters.

ExplanationH

Lifetimes: naming how long a borrow may last

Every reference has a lifetime: the stretch of the program during which it is valid. Inside one function the compiler works lifetimes out on its own. At function boundaries it sometimes needs your help, because it checks each function using only its signature. Consider:

rust
fn longer(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}
text
error[E0106]: missing lifetime specifier
 --> lt.rs:1:32
  |
1 | fn longer(a: &str, b: &str) -> &str {
  |              ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |          ++++     ++          ++          ++

The returned reference points into either a or b, so a caller must not use it after either argument is gone. The suggested signature says exactly that: for some lifetime 'a (pronounced "tick a"), both inputs live at least as long as 'a, and the result is valid for 'a. Lifetime annotations do not change how long anything lives; they describe relationships so the compiler can check them at each call.

rust
// The returned reference lives no longer than the shorter-lived of the two inputs.
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("  dropping {}", self.0);
    }
}

fn main() {
    let river = String::from("Mekong");
    {
        let other = String::from("Amazon River");
        let result = longer(&river, &other);
        println!("longer name: {result}");
    } // `other` is freed here, and `result` with it

    let _first = Noisy("first");
    {
        let _inner = Noisy("inner");
        println!("leaving the inner block");
    }
    let moved = Noisy("moved");
    let _new_owner = moved; // ownership moves; still dropped exactly once
    println!("end of main");
}
text
longer name: Amazon River
leaving the inner block
  dropping inner
end of main
  dropping moved
  dropping first

If you declare result before the inner block (let result;), assign it inside, and print it after the block has ended, the compiler rejects the program with error E0597, "other does not live long enough", and marks the line where other is dropped while still borrowed. That is the dangling-reference bug of C, caught at compile time.

You will write explicit lifetimes less often than this lesson suggests, thanks to the elision rules: if a function has exactly one reference parameter, or is a method taking &self or &mut self, the compiler assumes the output borrows from it. That is why first_word(text: &str) -> &str needed no annotation. You will also meet 'static, the lifetime of data that lasts for the whole program, such as string literals; when a compiler suggestion proposes 'static for a function that builds a new value, the right fix is almost always to return an owned value (String rather than &str) instead.

ExplanationH

Working with the borrow checker

What do experienced Rust programmers actually do when the borrow checker objects? A handful of habits cover most cases:

  • Borrow in parameters by default. Take &str, &[T] or &T unless the function genuinely needs to keep the value (store it in a struct, send it to another thread), in which case take it by value and let the caller decide whether to clone.
  • Return owned values from functions that create data. Returning a reference requires something to borrow from, and a local variable will be dropped when the function ends.
  • Shorten borrows. Many errors disappear if you finish using a reference before the mutation: copy the number you need out of a vector (let first = scores[0]; copies an i32) instead of holding a reference across push.
  • Clone when it is cheap and clear. Cloning a short string at the start of a program is not a crime. Profile before worrying, and don't clone large structures inside hot loops.
  • Use indexes or keys instead of long-lived references in complex data structures such as graphs. Store items in a vector and refer to them by position.
  • Read both spans of the error. Borrow errors point at two places, the borrow and the conflicting use; the fix is usually to move one of them.

When a design keeps fighting the rules, it is often a sign that two parts of the program both believe they own some data. Rust then offers explicit shared-ownership tools, Rc, Arc and RefCell, which lesson 9 covers. Reaching for them first, though, usually hides a design that could be simpler.

Common misconceptionsH

Common misconceptions

Misconception

"A move copies the whole value." Moving a String copies three machine words (pointer, length, capacity) and nothing on the heap; the optimiser often removes even that. Moves are cheap. What makes them meaningful is that the source can no longer be used.

Misconception

"Lifetime annotations make values live longer." They don't change any value's lifetime. They are constraints that let the compiler check that references are used only while their data is alive. If a value is dropped too soon, you must restructure the code, not annotate it.

Misconception

"A &mut reference is about mutation; & is about reading." That is the usual effect, but the deeper meaning is exclusive versus shared access. Some types (like Cell and Mutex, later in the course) allow carefully controlled changes through a shared reference, because they guarantee safety another way.

Misconception

"Functions should take &String." A &str parameter accepts everything a &String parameter accepts (thanks to deref coercion) plus string literals and slices of other strings. The same goes for &[T] versus a reference to a vector. Clippy, Rust's linter, flags &String parameters for this reason.

Exercises

Exercises

1. Ownership, borrowing and lifetimes

CoreComputational

Which of these main bodies compile? Choose all that apply.

Choose all that apply

2. Ownership, borrowing and lifetimes

CoreComputational

Noisy prints its name when dropped:

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("{}", self.0);
    }
}

fn main() {
    let _a = Noisy("a");
    let b = Noisy("b");
    {
        let _c = Noisy("c");
        drop(b);
    }
    println!("end");
}

What does it print? Write the four lines separated by spaces.

3. Ownership, borrowing and lifetimes

CoreComputational

What does println!("{}", "naïve".len()); print?

4. Ownership, borrowing and lifetimes

Warm-upComputational

What does this print?

fn main() {
    let s = "Bogotá";
    println!("{}", &s[0..4]);
}

5. Ownership, borrowing and lifetimes

CoreHuman

You are writing a function that counts the words in some text and returns the count. Which signature is most idiomatic?

Choose one

6. Ownership, borrowing and lifetimes

StretchHuman

What does the signature fn pick<'a>(x: &'a str, y: &str) -> &'a str promise?

Choose one

Further reading and resources