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

Ownership

Ownership in Rust is tied to memory management, so before going any further, let’s do a quick refresher on how programs manage memory. The Memory chapter covers this in more depth.

While a program runs, its data can live in three main places: the static segment, the stack and the heap.

  1. Static data lives for the whole execution of the program. Nothing is allocated or deallocated there at runtime.
  2. Stack data lives on the call stack. Each function call gets its own frame, which is freed when the function returns. The OS reserves the stack’s memory once, when a thread starts. The code generated by the compiler does the rest, allocating and freeing frames as functions are called and return. The programmer never has to allocate or free anything there.
  3. Heap data doesn’t follow the call stack, so it can’t be freed automatically when a function returns. Something has to decide when it’s no longer needed: the programmer, a garbage collector at runtime, or, in Rust’s case, rules the compiler checks.

Before Rust, there were two main approaches to managing data on the heap:

  • Manual memory management.
  • Garbage collection.

Manual memory management means programmers can make mistakes:

  • Forgetting to free leaks memory.
  • Freeing too early leaves a dangling pointer.
  • Freeing twice is undefined behavior.

Garbage collection is not free:

  • Scanning the heap takes CPU time away from the program.
  • Collections pause the program in an unpredictable manner.
  • The heap needs spare room for garbage to pile up between collections.

But what if there were a third way? What if the language’s type system could enforce how a program manages memory? That’s Rust’s approach, and ownership is at the heart of it.

Ownership is a set of rules that govern how a Rust program manages memory.

— The Rust Programming Language, ch. 4.1

The Rules

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.
  • A value is the combination of a type and an element of that type’s domain of values.
  • An owner is whatever holds the value: a variable, a struct field, an element of a collection or a Box.
  • A scope is the part of the code where a variable can be used.
fn main() {
    let s = String::from("hello"); // s owns the String
    {
        let t = s;                 // the String moves to t, s no longer owns anything
        println!("{t}");
    }                              // t goes out of scope: the String is dropped
    // println!("{s}");            // error[E0382]: borrow of moved value: `s`
}

Having a single owner per value and making it responsible for deallocating the data when it goes out of scope means that every allocation is paired with exactly one free1, and the compiler knows where that free happens. The programmer never has to remember to free anything, and no garbage collector has to run to find out what’s no longer used. Because there’s only ever one owner, the value can’t be freed twice. Because the owner frees it only when it goes out of scope, the value can’t be freed while the owner can still use it.

Moves

let t = s; in the example above is a move. To see what that actually does, look at what a String is in memory. Like the Vec in the Memory chapter, it’s three fields on the stack (a pointer, a length and a capacity) and the bytes themselves on the heap:

   stack frame of main               heap
 +----------------------+        +---+---+---+---+---+
 | s.ptr  --------------+------> | h | e | l | l | o |
 | s.len: 5             |        +---+---+---+---+---+
 | s.cap: 5             |
 +----------------------+

A move copies those three fields, bit for bit, into the new variable. The heap isn’t touched: nothing is allocated and the bytes don’t go anywhere.

   stack frame of main               heap
 +----------------------+        +---+---+---+---+---+
 | s.ptr  --------------+---+--> | h | e | l | l | o |
 | s.len: 5             |   |    +---+---+---+---+---+
 | s.cap: 5             |   |
 |                      |   |
 | t.ptr  --------------+---+
 | t.len: 5             |
 | t.cap: 5             |
 +----------------------+

Now two variables hold the same pointer. If both were owners, both would free the buffer when they went out of scope: a double free. That’s what rule 2 is for. After let t = s;, t is the owner and s is treated as uninitialized. Its bits are still sitting in the frame, because moving, like popping a frame or freeing a chunk, doesn’t erase anything. The compiler just won’t let you read them:

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

The compiler won’t drop s either. It tracks which variables still own something, and at the end of the scope it drops only those. That’s how every allocation stays paired with exactly one free: the buffer is freed once, through t. And since a moved-from variable is just uninitialized, not dead, you can give it a new value if it’s mut and use it again.

You can watch a move happen by printing where each variable lives and where its buffer is:

fn main() {
    let s = String::from("hello");
    println!("s on the stack: {:p}, s on the heap: {:p}", &s, s.as_ptr());

    let t = s;
    println!("t on the stack: {:p}, t on the heap: {:p}", &t, t.as_ptr());
}
$ cargo run
s on the stack: 0x7ffeac1090d8, s on the heap: 0x5580087c9d60
t on the stack: 0x7ffeac109140, t on the heap: 0x5580087c9d60
  • s and t have different addresses on the stack. They’re two variables, each with its own three fields.
  • The buffer address is the same. The bytes never moved, only the ownership did.

That makes a move cheap, and the cost doesn’t depend on the data: it copies 24 bytes on a 64-bit machine, whether the string holds 5 bytes or 5 GB.

The alternative would be to copy the heap buffer too, so each variable gets its own. That’s what .clone() does, and it’s why the compiler suggests it, but it costs an allocation and a copy of every byte. Rust never does that behind your back: for a String, a plain let t = s; is always a move.

Moves aren’t only about let. A value moves whenever it changes hands: when you assign it, pass it to a function, return it from one or push it into a Vec.

Copy and Clone

Not every let y = x; is a move, though. Try the same thing with an integer:

fn main() {
    let x = 5;
    let y = x;
    println!("x: {x}, y: {y}");
}

That compiles, and x is still usable. An i32 is four bytes on the stack and nothing else, so copying those bytes gives y a complete, independent value. There’s nothing for two owners to fight over. Types like that implement the Copy trait, and when you assign one, the compiler copies the bits and leaves the source usable. That’s what the error earlier meant by “String, which does not implement the Copy trait”.

So at the machine level a move and a copy are the same thing: the value’s bytes get copied, bit for bit. The only difference is whether the compiler lets you use the source afterwards. They even look the same in the code. The type decides which one you get.

A String can’t be Copy. Copying its bytes copies the pointer, not the buffer, and you’d be back to two owners and a double free. The compiler enforces this: a type can only be Copy if all its fields are, and never if it implements Drop. Integers, floats, bool, char, and tuples and arrays made of Copy types are all Copy. You can opt your own types in with #[derive(Clone, Copy)].

Clone is the deep copy the compiler suggested earlier. .clone() runs whatever code the type defines, and for a String that means a new allocation and a copy of every byte:

fn main() {
    let s = String::from("hello");
    let t = s.clone();
    println!("s on the heap: {:p}, t on the heap: {:p}", s.as_ptr(), t.as_ptr());
}
$ cargo run
s on the heap: 0x5eee9757fdd0, t on the heap: 0x5eee9757fdf0

Two buffers this time, each with its own owner. Every Copy type is also Clone, because Copy requires it, which is why the derive lists both. For those types .clone() just copies the bits.

What gets copiedSource usable after?Cost
Movethe value’s bytesnofixed, the size of the type
Copythe value’s bytesyesfixed, the size of the type
Clonewhatever the type decides, for a String the heap buffer tooyesdepends on the data

Drop

Rust deallocates memory by sneakily calling the drop method of the value’s type when its owner goes out of scope.

The compiler inserts that call at the closing brace of the owner’s scope, so you never write it yourself:

#![allow(unused)]
fn main() {
{
    let v = vec![1, 2, 3]; // allocates on the heap
    // ...
} // v goes out of scope: the compiler calls drop, which frees the heap buffer
}

drop comes from the Drop trait. Types that own heap memory either implement it or hold something that does, like String, which is a Vec<u8> under the hood.

You can implement Drop on your own types to run code when their values go away:

struct Noisy(&'static str);

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

fn main() {
    let _a = Noisy("a");
    let _b = Noisy("b");
    println!("end of main");
}
end of main
dropping b
dropping a

Summary

  • Heap memory needs someone to decide when it’s freed. Manual management risks leaks, dangling pointers and double frees. Garbage collection costs CPU time, pauses and spare memory. Rust has the compiler enforce a set of rules instead.
  • Every value has exactly one owner, and the value is dropped when its owner goes out of scope. That pairs every allocation with one free, at a place the compiler knows, with no garbage collector.
  • A move copies the value’s bytes and leaves the source uninitialized. The heap isn’t touched, so moving a String costs the same whether it holds 5 bytes or 5 GB. The compiler won’t let you read a moved-from variable, and won’t drop it either.
  • Copy types are copied instead of moved. Their bytes are a complete, independent value, so the source stays usable. Anything that owns a heap buffer or implements Drop can’t be Copy.
  • .clone() is the explicit deep copy. It runs whatever code the type defines: for a String, a new allocation and a copy of every byte. Rust never clones behind your back.
  • The compiler calls drop at the closing brace of the owner’s scope. That’s where heap memory gets freed, and you can implement Drop to run your own code when a value goes away.

  1. Strictly, at most one. Leaking memory is safe in Rust: std::mem::forget takes a value without ever dropping it, Box::leak gives up a heap allocation for the rest of the program, and two reference-counted pointers (Rc) that point at each other keep each other alive forever. Ownership guarantees that nothing is freed twice or while it’s still in use. It doesn’t guarantee that everything gets freed. ↩