Ownership and Borrowing

And what, Gul'dan, must we give in return?

Introduction

Programs inevitably deal with memory. Ideally, code should have two properties: first, memory objects should be freed promptly at the right time, giving us control over memory consumption; second, pointers to freed objects should never be used again, because doing so can cause crashes and vulnerabilities.

This divides programming languages into two broad camps:

  • Languages that pursue maximum performance through manual memory allocation and deallocation, leaving programmers responsible for avoiding memory leaks and dangling pointers, such as C, C++, Rust, and Zig.
  • Languages that trade some performance for automatic memory and pointer management through garbage collection (GC), a category that includes most modern languages.

To combine safety with performance, Rust takes a third approach: what we might call compile-time GC. It determines when memory should be freed during compilation and writes the corresponding instructions into the executable. This avoids runtime bookkeeping while providing memory and concurrency safety. To achieve this, Rust introduces two core concepts: ownership and lifetimes. Both are, at heart, restrictions on syntax that impose enough order to verify a program's safety at compile time. Ownership prevents double frees; lifetimes prevent dangling pointers and data races.

Rust's Memory Model

When a program runs, the operating system allocates address space and loads it into memory. Rust has not yet strictly defined its memory model, but we can broadly distinguish the following areas:

  1. Stack
    • The types and sizes of memory objects must be known at compile time.
    • Each function call receives a stack frame that stores its arguments and local variables.
  2. Heap
    • Memory is explicitly requested, usually for reading and writing larger amounts of data. Heap allocation is less efficient than stack allocation.
  3. Global storage
    • Holds the executable code itself.
    • Holds ordinary static functions, static variables, and string literals.

Ownership Rules

Rust's ownership system starts from two observations:

  1. The compiler can determine local variables' lifetimes and correctly manage stack memory through stack allocation and deallocation.
  2. Heap memory is ultimately accessed through pointers and references stored on the stack.

Could heap management become as straightforward as stack management, with the necessary instructions generated at compile time? Following this idea, Rust ties the lifetime of a heap allocation to a stack variable. When a function's stack frame is reclaimed and its local variables are destroyed, the corresponding heap memory, if any, is reclaimed through the destructor Drop::drop.

In C++, releasing an item's resources at the end of its lifetime is part of the pattern known as Resource Acquisition Is Initialization (RAII).

Consider an ordinary initialization statement:

1
2
3
4
5
fn main() {
    let Variable: Type = Value;
    // ...
    // Variable goes out of scope.
}

Variable is the variable, Type is its type, and Value is the memory object, also called the value. We call this a value binding: besides assigning a value to the variable, we give it ownership of the memory object.

A distinction in terminology: heap objects are managed through pointers on the stack. When Value includes heap memory, as in String::from("xxx") or Box::new(xxx), Variable strictly owns the stack representation containing the pointer. Because Type implements the destructor that reclaims the heap allocation, however, Variable effectively owns that allocation too. We can treat the stack representation and heap allocation as a whole. The essence of Rust ownership is making responsibility for releasing resources explicit.

The core ownership rules are simple:

  1. Every memory object has exactly one variable called its owner at any given time.
  2. When the owner goes out of scope, the memory object is freed.

The compiler knows when Variable goes out of scope, so it also knows when to reclaim Value. Having a unique owner prevents the same allocation from being freed twice.

Remember that ownership is a compiler abstraction. As a concept and a set of rules, it does not exist as an object in the running program.

Transferring Ownership

Other languages often distinguish shallow copies from deep copies. A shallow copy copies only a reference to a data object; a deep copy recursively follows references and copies the underlying data.

To accommodate its ownership system, Rust instead distinguishes moves, copies, and clones.

Move Semantics

Consider the following code:

1
2
3
4
5
6
7
8
9
let mut s1 = String::from("big str");
let s2 = s1;

// This produces: error: borrow of moved value: `s1`
println!("{},{}", s1, s2);

// Reinitialize the variable.
// "big str" will be freed automatically; new heap memory is allocated for "new str".
s1 = String::from("new str");

What should happen when s1 is assigned to s2? Copying s1's pointer representation into s2 while leaving both owners valid would violate unique ownership and cause a double free. Copying the heap allocation into a new allocation for s2 would conflict with Rust's emphasis on performance.

Instead, Rust transfers ownership. It invalidates s1: the variable still exists, but loses ownership and becomes uninitialized. If s1 is mutable, it can be initialized again. Rust copies the stack representation and gives ownership of the memory object to s2, which now points to the same heap allocation:

Moving ownership

The compile-time mut annotation applies to a variable binding rather than to the memory object. An immutable s1 therefore does not prevent us from introducing a mutable s2 that writes to that memory:

1
2
3
4
5
// s1 is immutable.
let s1 = String::from("big str");

let mut s2 = s1;
s2.push('C');  // Valid.

Ownership Checking

Ownership checking is static analysis performed at compile time. The compiler generally reasons from the code's structure rather than trying to predict its execution, which can make it seem less clever than we expect. For example, given two separate if statements with mutually exclusive conditions, it simply reports that x cannot be moved twice:

1
2
3
4
5
6
7
8
fn foobar(n: isize, x: Box<i32>) {
    if n > 1 {
        let y = x;
    }
    if n < 1 {
        let z = x; // error[E0382]: use of moved value: `x`
    }
}

It does not even recognize that a move inside this for loop executes only once:

1
2
3
4
5
fn foobar(x: Box<i32>) {
    for _ in 0..1 {
        let y = x; // error[E0382]: use of moved value: `x`
    }
}

Compiler Optimizations

Moves occur not only in assignments but also when passing function arguments and returning values. Passing a large object, such as a long array or a struct with many fields, could therefore affect performance.

The Rust compiler can optimize this behavior. Broadly speaking, when an object is large and correctness permits it, the compiler may pass a pointer to the object instead of copying its memory.[1]

Although move semantics conceptually copy the stack representation, the performance impact is therefore usually limited.

Copy Semantics

Invalidating the source variable on every assignment would be inconvenient. Rust therefore provides copy semantics, whose difference from a move is that the original variable remains usable. A copy behaves like a shallow copy: it duplicates the stack representation bit for bit without taking responsibility for a separate heap allocation. The old and new variables each bind to independent stack values and own those values. If both were responsible for the same heap allocation, this would cause a double free. Rust therefore uses moves by default and only copies values whose types implement the Copy trait.

The standard library's i32, for example, implements Copy, so assignment uses copy semantics instead of move semantics, leaving the source variable usable.

Types that implement Copy include, but are not limited to:

  • All integer types.
  • All floating-point types.
  • Booleans.
  • Characters.
  • Tuples, if and only if all their component types implement Copy. For example, (i32, i32) is Copy, but (i32, String) is not.
  • Raw constant pointers *const T and shared references &T, regardless of whether T implements Copy.

Copy is a marker trait with no methods to override. It simply tells the compiler that a type can be copied bit for bit. Programmers cannot customize what copying does. For a custom type, Copy is usually derived with #[derive], together with Clone:

1
2
#[derive(Copy, Clone)]
struct MyStruct(i32, i32);

It can also be implemented using impl:

1
2
3
4
5
6
7
8
9
struct MyStruct;

impl Copy for MyStruct {}

impl Clone for MyStruct {
    fn clone(&self) -> MyStruct {
        *self
    }
}

The two approaches are equivalent for these purposes. A type can implement Copy only when all its components implement Copy. A "component" may be a struct field, an enum variant's field, an array element, a tuple item, and so on.

The standard library documentation notes[2] that, generally speaking, a type that can implement Copy should do so. However, implementing Copy becomes part of the type's public API. If the type might become non-Copy in the future, omitting the implementation now may avoid a later breaking change.

Which types cannot implement Copy? Drop and Copy are mutually exclusive: a type that implements Drop, or contains a component that does, cannot implement Copy. Examples include String and Vec<T>.

The Drop trait defines just one method, the destructor drop:

1
2
3
pub trait Drop {
    fn drop(&mut self);
}

When a value is no longer needed, for example when it leaves scope or is overwritten, Rust runs its destructor. Destruction of a type T includes:

  1. Calling <T as std::ops::Drop>::drop if T implements Drop.
  2. Running automatically generated "drop glue" to recursively destroy its components:
    • Struct fields are dropped in declaration order.
    • Fields of the active enum variant are dropped in declaration order.
    • Tuple fields are dropped in order.
    • Array and slice elements are dropped from first to last.
    • The order for variables captured by move in a closure is unspecified.
    • Dropping a trait object runs the destructor of its underlying concrete type.
    • Other types require no further destruction.

You usually do not need to implement Drop yourself. For types that manage resources directly, however, a manual implementation is necessary. Those resources might be memory, file descriptors, or network sockets. Once a value is no longer used, its resources should be cleaned up promptly by freeing memory or closing the file or socket. That is the destructor's job, and the responsibility of Drop::drop.

To avoid releasing resources twice, the compiler forbids explicit calls to Drop::drop. Sometimes, however, a variable needs to be dropped early, such as a mutex guard. The standard library provides the callable function std::mem::drop for this purpose:

1
pub fn drop<T>(_x: T) { }

There is no magic in this empty function. It accepts a value of any type and does nothing with it. Ownership moves into std::mem::drop, and the value is automatically dropped before the function returns.

Mutable references &mut T also do not implement Copy, because copying them would violate the borrowing rules.

Clone Semantics

You may have noticed the Clone trait above. A value of a type implementing Clone has a clone() method that explicitly copies it. The implementation is responsible for producing a valid duplicate, potentially copying both stack and heap data, much like a deep copy. Clone is also a supertrait of Copy:

1
pub trait Copy: Clone { }

A type that implements Copy must therefore also implement Clone. For a Copy type, the clone() implementation only needs to return *self.

1
2
3
4
let s1 = String::from("big str");
// After cloning, s1 still binds to the original data.
let s2 = s1.clone();
println!("{},{}", s1, s2);

A straightforward Clone implementation can be expensive, but developers can optimize it for their types. For example, cloning an Rc increments its reference count and copies only a small amount of data.

Summary

A move is like a shallow copy followed by invalidation of the original variable: it copies the stack representation and transfers ownership. A copy performs a shallow copy while leaving both values usable. A clone must be requested explicitly and can duplicate both stack and heap data to produce another owned value.

Moves and copies happen implicitly during assignment, argument passing, and returning values. Cloning requires an explicit call to Clone::clone(&self).

Ownership Trees

A variable of a compound type, such as a tuple, array, vector, struct, or enum, forms an ownership tree with its components. When a component A moves or goes out of scope, its children follow it. After A is moved, its ancestors cannot be used as complete values until A is reinitialized, although components outside A remain usable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#[derive(Debug)]
struct Vector {
    x: Vec<i32>,
    y: Vec<i32>,
}

fn main() {
    let mut v1 = Vector {
        x: vec![1, 2, 3, 4, 5],
        y: vec![6, 7, 8, 9, 10],
    };
    let x = v1.x;
    println!("{:?}", x);
    println!("{:?}", v1.y);
    // println!("{:?}", v1); // Error: borrow of partially moved value: `v1`
    v1.x = vec![11, 12, 13, 14, 15]; // Reinitialize v1.x to make the whole value usable again.
    println!("{:?}", v1);
}

Borrowing

Like C and C++, Rust has pointer and reference types: shared references &T, mutable references &mut T, raw constant pointers *const T, and raw mutable pointers *mut T. Their values are memory addresses of objects of type T, and dereferencing them accesses those objects.

The difference is that dereferencing a raw pointer is unsafe and requires an unsafe block. References are pointers restricted by the compiler: they follow borrowing rules that are checked to ensure safety.

For convenience, the lifetime of a Rust reference can be shorter than the surrounding variable's lexical scope. An ordinary variable's scope runs from its initialization to the nearest closing brace }; a reference's relevant lifetime runs from the borrow to its last use. This behavior is known as non-lexical lifetimes (NLL).

Creating a reference is called borrowing: the reference borrows access to the memory object instead of acquiring ownership. Borrowing lets us access an object without transferring ownership:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fn main() {
    let s1 = String::from("hello"); // s1 contains a pointer to heap memory.

    let len = calculate_length(&s1); // An immutable borrow occurs here.

    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize { // s is a reference to s1.
    s.len()
}

calculate_length() receives a shared reference to s1. The parameter s borrows access to it:

Borrowing through a shared reference

Rust has three basic borrowing rules:

  • While a shared reference is valid, the referenced object can only be borrowed through further shared references and accessed read-only.
  • While a mutable reference is valid, the original object cannot be accessed directly or borrowed again through the original binding.
  • References must always be valid: a reference's lifetime cannot exceed that of the original value. An owner therefore cannot move its value while it is borrowed, although copying or cloning remains possible where the relevant rules permit it.

In other words, at any given time there can be either one mutable reference or any number of shared references. This is why &mut T does not implement Copy: copying it would readily violate the borrowing rules. Shared references, in contrast, can be copied and remain usable after assignment to another reference variable.

Why these rules? Rust wants a resource to be read and written through at most one name, or read through several names, at any given time. The following code therefore fails:

1
2
3
4
5
6
7
8
fn main() {
    let mut x = 0;
    let y = &mut x; // y mutably borrows x.
    if x == 0 { // Error: x cannot be read or written directly while y's mutable borrow is active.
        *y += 1; // The lifetime of y's borrow ends here.
        println!("{}", x); // x can be read again here.
    }
}

Dereferencing

Dereferencing *r gives us what we might call a shadow variable: an alias without ownership. It lets us read or write a memory object, but not move ownership out of it, which would undermine the original owner's control. Copying or cloning is still possible:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
struct MyType<T> {
    val: T
}

fn main() {
    let num1 = 1;
    let num1_ref = &num1;
    let num2 = *num1_ref; // i32 is Copy, so copying through *num1_ref leaves the original ownership intact.

    let x = MyType{val: 1};
    let y = &x;
    let z = *y; // Error: MyType<i32> is not Copy, so ownership cannot be moved through *y.
}

Ownership of References

Every value in Rust has ownership, including reference values. A reference does not own the object it points to, but a reference variable owns its own address value:

1
2
3
4
5
6
fn main() {
    let mut s = String::from("value");
    let r = &mut s; // r is a mutable reference to s.
    let _r1 = r; // A move, not a copy.
    let _r2 = r; // Error: use of moved value: `r`
}

Shared references implement Copy and therefore also Clone. The following Person struct does not implement Clone, so b.clone() can only copy the reference b, rather than the object it points to. This compiles, but Clippy discourages it: it is effectively a copy and probably not the clone the programmer intended.

1
2
3
4
5
6
7
8
struct Person;

fn main() {
    let a = Person;
    let b = &a;
    // Warning: the type `Person` does not implement `Clone`, so calling `clone` on `&Person` copies the reference, which does not do anything and can be removed.
    let _c: &Person = b.clone();
}

If we implement Clone for Person, calling clone() through the reference no longer produces that warning:

1
2
3
4
5
6
7
8
#[derive(Clone)]
struct Person;

fn main() {
    let a = Person;
    let b = &a;
    let _c: Person = b.clone(); // _c now has type Person, rather than &Person.
}

The only difference is whether the referenced type, Person, implements Clone. Method lookup searches for methods matching the receiver type in a particular order and stops when it finds one. Because . can automatically borrow and dereference, multiple candidate receiver types may implement the same method. Rust chooses according to the lookup order.[3]

If b is a mutable reference, which implements neither Copy nor Clone, b.clone() can only produce a Person, provided Person implements Clone.

A Memory Diagram

This diagram illustrates variables, types, memory objects, values, references, dereferencing, and raw pointers:

Variables, values, references, and pointers in memory

Reborrowing

As discussed above, borrowing rules prohibit multiple active mutable references to an instance, or active shared and mutable references at the same time. Borrowing through the shadow variable obtained by dereferencing, however, is allowed. This is called reborrowing:

1
2
3
4
5
6
7
8
let mut s = String::from("ABC");
let r1 = &mut s;
{
    let r2 = &mut *r1; // Reborrow.
    r2.push('2');
    println!("{}", r2); // r2's borrow ends here.
}
println!("{}", r1); // r1's borrow ends here.

Inside the braces, r1 and r2 are both mutable references ultimately pointing to s, yet the compiler accepts the code. The borrow checker reasons about the access path *r1 rather than treating it as a fresh direct borrow of s.

Reborrowing follows rules similar to borrowing:

  • While an immutable reborrow is valid, the original reference can only be reborrowed immutably and used for read-only access.
  • While a mutable reborrow is valid, the original reference cannot be accessed or used to create another conflicting reborrow.

Reborrowing a mutable reference effectively divides access into smaller, non-overlapping lifetimes within the original borrow. Non-overlapping access preserves the rule: "At any given time, you can have either one mutable reference or any number of immutable references."

1
2
3
4
5
6
7
8
9
struct A(i32,i32);
impl A {
    fn foo(&mut self) {
        let a = &self.0; // Equivalent to let a = &(*self).0;
        self.bar(); // Equivalent to bar(&mut *self);
        a;
    }
    fn bar(&mut self) {}
}

This fails because self.0 immutably reborrows part of self, while self.bar() mutably reborrows all of self, including the path to its first field. Changing the signature of bar() to fn bar(&self) makes it compile.

Implicit Reborrowing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let mut s = String::from("ABC");
let r1 = &mut s;
{
    let r2 = &mut *r1;

    let l = r1.len(); // Error: cannot borrow `*r1` as immutable because it is also borrowed as mutable.
    println!("{}", l);
    r2.push('2');
    r1.push('3'); // Error: cannot borrow `*r1` as mutable more than once at a time.
    println!("{:?}", r1); // Error: cannot borrow `r1` as immutable because it is also borrowed as mutable.
    println!("{}", r2);
}
println!("{}", r1);

Why do the error messages mention *r1 when we passed a reference to the method? Because an implicit reborrow occurs. r1.len() is effectively String::len(&*r1), and r1.push('3') is effectively String::push(&mut *r1, '3').

This is useful rather than redundant. The method signatures are pub fn len(&self) -> usize and pub fn push(&mut self, ch: char). Implicit reborrowing supplies the appropriate shared or mutable reference and prevents the call to push() from moving r1, which would make it unusable afterward.

Implicit reborrowing is widespread:

1
2
3
4
5
6
7
8
let mut s = String::from("ABC");
let r1 = &mut s;
// Without a type annotation, this moves r1 instead of reborrowing it.
let r2 = r1;
// An explicit reference type enables implicit reborrowing; the same applies to function arguments.
let r3: &mut String = r2; // Equivalent to let r3: &mut String = &mut *r2;
println!("{:?}", r3);
println!("{:?}", r2); // These two print statements cannot be reversed.

For a shared reference &T, we can think of this as either reborrowing or copying, because the result is the same.

Explicit Reborrowing

In the following two cases[4], from() does not automatically reborrow:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct X;

impl From<&mut i32> for X {
    fn from(i: &mut i32) -> Self {
        X
    }
}

fn from_auto_reborrow<'a, F, T: From<&'a mut F>>(f: &'a mut F) -> T {
    T::from(f)
}

fn from<F, T: From<F>>(f: F) -> T {
    T::from(f)
}

fn main() {
    let mut i = 4;
    let r = &mut i;

    let _x: X = from_auto_reborrow(r); // Implicit reborrow.

    let _x: X = from(&mut *r); // Explicitly reborrow to avoid moving r.
    let _x: X = from(r); // No implicit reborrow: r moves.
    let _x: X = from(r); // Compilation fails.
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct I(i32);
struct X;

impl From<&mut I> for X {
    fn from(p: &mut I) -> X {
        p.0 = 1;
        X
    }
}

// This intermediate function is necessary.
fn x_from(p: &mut I) -> X {
    X::from(p)
}

// Error: value used here after move.
fn from_twice_fail(p: &mut I) {
    let _x1 = X::from(p); // No automatic reborrow here: p moves.
    let _x2 = X::from(p); // Compilation fails.
}

fn from_twice(p: &mut I) {
    let _x1 = x_from(p); // Implicit reborrow.
    let _x2 = x_from(p); // Compiles.
}

Here are a few hypotheses about this behavior:

  1. Reborrowing is a type coercion. The coercion rules suggest that it may only occur when both the source and target types are known.
  2. Type inference in rustc may not yet be complete at that point, so whether some values are references remains unknown and reborrowing does not occur.
  3. Arguments may be analyzed from first to last. Information inferred while analyzing an earlier argument can then be used when analyzing later arguments.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
struct A;
struct B;

trait Hey<T> {
    fn hey(p: T, q: T);
}

impl Hey<u32> for B {
    fn hey(p: u32, q: u32) { todo!() }
}

impl Hey<&mut A> for B {
    fn hey(p: &mut A, q: &mut A) { todo!() }
}

fn hey_hey(p: &mut A, q: &mut A) {
    // The _ in <B as Hey<_>> has two possible types and must be inferred.
    <B as Hey<_>>::hey(p, q);
    // The compiler reports that p has moved, while q remains usable.
    <B as Hey<_>>::hey(p, q);
}
Refresh