My account

Ownership and borrowing in Rust

Rust has no garbage collector, but it still frees memory safely. The trick is ownership. Every value has one owner, a move gives the value to a new owner, and a borrow lets other code use the value for a while. The compiler checks these rules before the program runs. Once you see why each rule exists, most borrow checker errors become easy to read and to fix.

Not reviewedWritten with AI helpReading time: 18 minOnline shop exampleRust 2024 edition

Author: bezzad

Contents

The problem: who frees the memory?

Our online shop keeps the cart of each user in memory. A cart has a list of items, and the list lives on the heap. At some point this memory must be given back. Languages solve this in two common ways:

  1. By hand (C, C++). The programmer frees the memory. If they free it twice, or use it after it is freed, the program can crash or, worse, leak data. These bugs are a big source of security holes.
  2. With a garbage collector (Java, C#, Go). A runtime finds memory that nobody uses and frees it later. It is safe, but it costs CPU time and memory, and the pauses are not fully under your control.

Rust takes a third way. The compiler knows exactly one owner for every value. When the owner goes away, the value is freed. All of this is checked at compile time, so there is no runtime cost and no garbage collector.

The three ownership rules

  1. Each value has one owner. The owner is a variable, a struct field, or an item in a collection.
  2. There is only one owner at a time.
  3. When the owner goes out of scope, the value is dropped. Rust calls the drop function for you, and the memory is freed.
fn main() {
    let customer = String::from("Sara"); // customer owns the text
    println!("{customer}");
} // customer goes out of scope here: the text is freed

The closing curly brace is where the memory is freed. You never call free yourself, and you cannot forget it.

A move gives the value to a new owner

What happens when we assign a String to another variable?

fn main() {
    let sku = String::from("shoe-42");
    let order_sku = sku; // the value moves to order_sku

    println!("{order_sku}");
    // error[E0382]: borrow of moved value: `sku`
    // println!("{sku}");
}
  1. A String has two parts. On the stack there is a small header: a pointer, a length and a capacity. The text itself is on the heap.
  2. The assignment copies only the header. Now two headers point to the same heap buffer.
  3. If both were owners, both would free the same buffer at the end of the scope. That is a double free.
  4. So Rust says the value moved. The old variable sku is no longer valid, and the compiler rejects any later use of it.
StackHeapskuptr | len 7 | cap 7moved: cannot be usedorder_skuptr | len 7 | cap 7the only ownershoe-42Freed exactly once,when order_sku is dropped
After the move, only order_sku owns the heap buffer. The old variable sku can no longer be used, so the buffer is freed exactly once.

Passing a value to a function is also a move:

fn save_order(sku: String) {
    println!("saving {sku}");
} // sku is dropped here

fn main() {
    let sku = String::from("shoe-42");
    save_order(sku); // moved into the function
    // error[E0382]: use of moved value: `sku`
    // save_order(sku);
}

The function now owns the text, and it frees it when it ends. If the caller still needs the value, the function should borrow it instead.

Copy and Clone

Not every assignment is a move. Small values that live only on the stack are simply copied:

fn main() {
    let quantity: u32 = 2;
    let copy = quantity; // u32 is Copy: both are valid
    println!("{quantity} {copy}");
}
  1. Copy types are copied bit by bit, and the old variable stays valid. Integers, floats, bool, char and shared references are Copy. A tuple or an array is Copy if everything inside it is Copy.
  2. A type can be Copy only if all its fields are Copy and it has no custom drop. String and Vec own heap memory and free it in their drop, so they are never Copy.
  3. Clone is an explicit, possibly expensive copy. Calling the clone method on a String makes a new heap buffer with the same text. You write it on purpose, so the cost is visible in the code.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Money {
    cents: u64,
}

#[derive(Debug, Clone)]
struct CartItem {
    sku: String, // String is not Copy, so CartItem cannot be Copy
    quantity: u32,
    price: Money,
}

A clone call to make the borrow checker quiet is a common smell in code review. Often a borrow is the better fix.

Borrowing: use a value without owning it

A reference lets code use a value without taking ownership. Creating a reference is called borrowing.

fn cart_total(items: &[CartItem]) -> u64 {
    items
        .iter()
        .map(|item| item.price.cents * u64::from(item.quantity))
        .sum()
}

fn add_item(items: &mut Vec<CartItem>, item: CartItem) {
    items.push(item);
}

fn main() {
    let mut cart = Vec::new();
    let shoe = CartItem {
        sku: "shoe-42".into(),
        quantity: 1,
        price: Money { cents: 4999 },
    };
    add_item(&mut cart, shoe);
    println!("total: {}", cart_total(&cart)); // cart is still ours
}

There are two kinds of references:

  1. A shared reference, written with an ampersand. You can only read through it. Many shared references can exist at the same time.
  2. A mutable reference, written with an ampersand and the mut keyword. You can change the value through it. While it exists, no other reference to the same value may be used.

So the rule is: many readers or one writer, never both at once. People also call it “aliasing XOR mutability”.

Many readers&cart&cart&cartcartRead only, at the same timeOne writer&mut cart&cartnot allowedcartRead and write, nobody else
At any moment a value has either many shared references (only reading) or exactly one mutable reference (reading and writing). Never both.

Why the borrow rules exist

The rule can feel strict. Here is the bug it stops:

fn main() {
    let mut cart = vec![String::from("shoe-42")];

    let first = &cart[0]; // shared borrow of cart
    // error[E0502]: cannot borrow `cart` as mutable
    cart.push(String::from("hat-m"));
    println!("{first}");
}
  1. The variable first points into the vector’s heap buffer.
  2. The push method may need more space. Then it moves all items to a new, bigger buffer and frees the old one.
  3. After that, first would point to freed memory. In C++ this compiles and is a real bug class (iterator invalidation).
  4. Rust refuses to compile it. You cannot change the vector while a shared borrow of it is still used later.

The borrow lasts only until its last use, not until the end of the block. So this version compiles:

fn main() {
    let mut cart = vec![String::from("shoe-42")];

    // own a copy, or finish using the borrow before the push
    let first = cart[0].clone();
    println!("first: {first}");
    cart.push(String::from("hat-m"));
}

Lifetimes: how long a borrow is valid

A reference must never live longer than the value it points to. The compiler tracks this with lifetimes. Most of the time you do not write them, because the compiler fills them in. You must write them when the compiler cannot guess.

// Which input does the result borrow from? The compiler cannot know.
fn longer_name<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}
  1. The name ’a is a lifetime parameter. It is a label, not a real duration.
  2. The signature says: the result is valid as long as both inputs are valid.
  3. Lifetimes do not change how long values live. They only describe it, so the compiler can check the callers.

When a function has exactly one reference input, or a method has a self reference, the compiler applies the elision rules and you can skip the labels:

fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

A common mistake is to return a reference to a local value:

// error[E0106]: missing lifetime specifier
fn order_label(order_id: u64) -> &str {
    let label = format!("Order #{order_id}");
    &label // label is freed at the end of this function
}

No lifetime label can fix this, because the String really dies when the function ends. The fix is to return the owned String.

Structs that hold references

A struct can hold a reference, but then it needs a lifetime parameter, and it can never outlive the data:

struct ReceiptLine<'a> {
    name: &'a str,
    cents: u64,
}

This is useful for short-lived views, for example while parsing a big text. For data that lives long, like an order in a queue or in shared state, own the data (use String, not a string reference). It makes the code much simpler.

String and str

Rust has two main text types, and the difference follows the ownership idea:

  1. String owns its text. The text is on the heap, and it can grow.
  2. A string slice (the str type, used behind a reference) is a borrowed view into some text. It is only a pointer and a length. It can point into a String, into a string literal in the program binary, or into part of another text.
fn main() {
    let mut name = String::with_capacity(16); // room for 16 bytes
    name.push_str("Sara Karimi"); // 11 bytes used
    let first: &str = &name[..4]; // "Sara": a view, no copy
    println!("{first}");
}
SaraKariminame: Stringptr | len 11 | cap 16owns the bufferfirst: &strptr | len 4borrows a part of itHeap buffer, capacity 16unused spaceThe slice sees only SaraNo copy, no new buffer
A String owns a growable heap buffer. A string slice is only a pointer and a length that borrows some or all of that text.

The numbers in a slice range are byte positions, not letters. If a range cuts a multi-byte letter (for example a Persian letter) in half, the program panics.

fn normalize_sku(sku: &str) -> String {
    sku.trim().to_ascii_uppercase()
}

fn main() {
    let from_form = String::from("  shoe-42 ");
    // a reference to a String works, and a literal works too
    println!("{}", normalize_sku(&from_form));
    println!("{}", normalize_sku("hat-m"));
}
  1. Take a string slice as a parameter when the function only reads the text. It accepts a String (through automatic deref coercion), a literal, and a part of a text.
  2. Return a String when the function creates new text.
  3. Take a String parameter only when the function needs to keep the text, for example to store it in a struct. Then the caller can move it in without a copy.
  4. The same idea applies to lists. A slice parameter is more flexible than a reference to a Vec.

Common mistakes

Mistake Result Better way
Using a variable after moving it Compile error E0382. Borrow instead of moving, or clone on purpose.
Calling clone everywhere to silence the compiler Extra heap work, hidden design problems. Borrow, or change who owns the data.
Keeping a reference into a Vec and then pushing Compile error E0502. Finish using the reference first, or store an index or an owned copy.
Returning a reference to a local value Compile error (missing lifetime or E0515). Return the owned value.
A reference to a String or a Vec as a parameter Callers with a literal or a slice must allocate. A string slice or a slice parameter.
References inside long-lived structs Lifetime parameters spread everywhere. Own the data in the struct.
Thinking lifetimes make values live longer Confusion and wrong fixes. Lifetimes only describe; change the owner instead.

Summary in 7 lines

  1. Every value has exactly one owner. When the owner goes out of scope, the value is dropped.
  2. Assignment and passing by value move ownership. The old variable cannot be used anymore.
  3. Copy types are copied bit by bit. Clone is an explicit and possibly expensive copy.
  4. Many shared references or one mutable reference, never both at once.
  5. These rules stop use-after-free and iterator invalidation at compile time.
  6. Lifetimes only describe how long a borrow is valid. They never extend a value’s life.
  7. Take a string slice when you only read text, and return a String when you create it.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.