Skip to content
RustLearn

Module 05 — Borrowing, References & Slices

Goal

Lend data instead of giving it away. The borrow checker's two rules, mutable vs shared references, and slices as borrowed views into data.

Start here — what this module is really about

Module 04 left you with a real problem: if handing a value to a function gives it away, then reading something means losing it. That is unworkable, and this module is the fix.

A reference lets you use a value without owning it. You write &value to make one, and a function signature says &Type to accept one. Nothing is copied, nothing is given away, and when the reference goes out of scope nothing is cleaned up — because a reference never owned anything in the first place. This is called borrowing, and it is how the overwhelming majority of Rust code passes data around.

There are two kinds, and the difference is the whole module:

  • &T — a shared reference. Read-only. You may have as many as you like at once.
  • &mut T — a mutable reference. Read and write. You may have exactly one, and no shared ones at the same time.

That second rule is the one people fight. It is worth understanding why it exists rather than memorising it: if one part of your code can change a value while another part is reading it, then what the reader saw a moment ago may no longer be true. That is the root of data races between threads (module 17) and of a whole family of single-threaded bugs — a loop reading a list while something else adds to it, for example. Rust makes the arrangement impossible rather than asking you to be careful.

All of it is checked at compile time and costs nothing when the program runs.

The one sentence to remember: many readers or one writer, never both at once.

Learning objectives

  • Use &T and &mut T to access data without taking ownership
  • State and apply the borrowing rules
  • Understand non-lexical lifetimes (why some "obviously fine" code now compiles)
  • Read and fix E0499, E0502, E0506, E0596
  • Use slices (&[T], &str) and write functions that accept the widest input

5.1 References solve module 04's tedium

rust
fn calculate_length(s: &String) -> usize {
    s.len()
}                              // s goes out of scope, but it doesn't own the data,
                               // so nothing is dropped

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);
    println!("'{s1}' has length {len}");   // ✅ s1 still owned by main
}

&s1 creates a reference: a pointer that is guaranteed by the compiler to be valid and non-null for as long as it exists. Creating a reference is called borrowing.

s1 ┌──────────┐         heap
   │ ptr ─────┼───────► "hello"
   │ len 5    │  ▲
   │ cap 5    │  │
   └──────────┘  │
s  ┌──────────┐  │
   │ ptr ─────┼──┘         (a reference to s1, not to the heap directly)
   └──────────┘

By default references are immutable — you cannot change what you borrowed:

rust
fn push(s: &String) {
    // s.push_str(" world");   // ❌ E0596: cannot borrow `*s` as mutable
}

Analogy — lending the book

Module 04 left you handing your only copy of a book to anyone who wanted to read a page, and asking for it back at the end. Borrowing is lending it: they read it, you still own it, and it returns to your shelf automatically. Nearly every function that felt clumsy last module wanted a borrow, not the deed.

5.2 Mutable references

rust
fn add_world(s: &mut String) {
    s.push_str(", world");
}

fn main() {
    let mut s = String::from("hello");   // the OWNER must be `mut` too
    add_world(&mut s);
    println!("{s}");                     // hello, world
}

Three muts must line up: the binding (let mut s), the reference creation (&mut s), and the parameter type (&mut String).

Automatic dereferencing

rust
let mut n = 5;
let r = &mut n;
*r += 1;             // explicit deref for primitives
println!("{n}");     // 6

let mut s = String::from("hi");
let r = &mut s;
r.push('!');         // no `*` needed: method calls auto-deref

Rust inserts * automatically for method calls (this is "auto-deref"), but you need it for direct assignment or arithmetic through a reference.

5.3 The borrowing rules

Note

At any given time, you may have EITHER one mutable reference, OR any number of immutable references — never both. References must always be valid.

This is the single rule that eliminates data races at compile time.

Rule 1: no two mutable borrows

rust
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;      // ❌ E0499: cannot borrow `s` as mutable more than once
println!("{r1} {r2}");

Rule 2: no mutable borrow while immutable borrows are alive

rust
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;          // ✅ many shared borrows are fine
let r3 = &mut s;      // ❌ E0502: cannot borrow `s` as mutable because it is
                      //    also borrowed as immutable
println!("{r1} {r2} {r3}");

Rule 3: references must not outlive the data

rust
fn dangle() -> &String {          // ❌ E0106 / E0515
    let s = String::from("hello");
    &s                            // s dies here; the reference would dangle
}

fn no_dangle() -> String {        // ✅ move ownership out instead
    String::from("hello")
}

In C this compiles and gives you a use-after-free. In Rust it is a compile error. That's the whole value proposition in four lines.

Why these rules?

A data race requires: two or more accesses to the same location, at least one write, and no synchronization. The borrowing rules make it impossible to have a writer and any other accessor simultaneously — so data races cannot be expressed. The same rules also eliminate iterator invalidation and aliasing bugs in single-threaded code:

rust
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);            // ❌ E0502 — push may reallocate, invalidating `first`
println!("{first}");

In C++ this is a classic dangling-pointer bug. Rust refuses to compile it.


Why "one writer" is a rule and not a suggestion

Here is the shape of the bug the rule prevents, in a single thread:

rust
let mut names = vec![String::from("ana")];
let first = &names[0];            // a shared reference into the list
names.push(String::from("bo"));   // ❌ E0502 — needs &mut while `first` is alive
println!("{first}");

Without the rule this compiles and is a genuine use-after-free. Here is why: a Vec keeps its items in one contiguous block of heap memory. When it runs out of room, push allocates a bigger block, copies everything across, and frees the old one. first still points into the old block — which no longer belongs to your program. Reading it might give the right answer, or garbage, or a crash, depending on what the allocator did next.

The compiler's message names exactly this:

text
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable

Read it as: something is still reading this, so I will not let anything change it.

The fix is almost always to shorten the read, not to fight the checker:

rust
let mut names = vec![String::from("ana")];
println!("{}", &names[0]);        // the borrow ends at the end of this line
names.push(String::from("bo"));   // ✅ nothing is reading any more

This is also why §5.4's non-lexical lifetimes matter: a borrow ends at its last use, not at the closing brace. Moving a println! up a few lines genuinely fixes errors, and that is not a hack — it is you telling the compiler the truth about when you stopped reading.

Analogy — the shared document

Any number of people may read a document at once and never disagree about what it says. The moment one person is allowed to edit it, everyone else must put it down — otherwise someone quotes a sentence that no longer exists. That is the borrowing rule in full: many readers, or one writer, never both. It is not Rust being possessive; it is the only arrangement in which what you read is still true when you act on it.

5.4 Non-lexical lifetimes (NLL)

A borrow ends at its last use, not at the end of the block:

rust
let mut s = String::from("hello");

let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");     // last use of r1, r2 -> their borrows END here

let r3 = &mut s;           // ✅ now allowed
println!("{r3}");

This is why code that "looks like it should be fine" usually is. When you hit a borrow error, first ask: is the earlier borrow still used after this point? If not, the borrow is already over and something else is wrong; if yes, that's your conflict.

A common shape and its fix:

rust
// ❌ the borrow from get() lives across the mutation
let mut map = std::collections::HashMap::new();
map.insert("a", 1);
let v = map.get("a").unwrap();
map.insert("b", 2);        // E0502
println!("{v}");

// ✅ end the borrow early by copying out what you need
let v = *map.get("a").unwrap();
map.insert("b", 2);
println!("{v}");

5.5 Slices

A slice is a borrowed view into a contiguous sequence: a pointer plus a length. It owns nothing.

String slices

rust
let s = String::from("hello world");

let hello = &s[0..5];      // &str
let world = &s[6..11];
let whole = &s[..];        // whole string
let head  = &s[..5];       // from start
let tail  = &s[6..];       // to end

Gotcha

Slice indexes are byte offsets, and slicing in the middle of a UTF-8 character panics at runtime. &"héllo"[0..2] panics. Use .chars() or char_indices() when working with non-ASCII text (module 09).

The classic first_word

rust
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    s
}

Why this signature is the right one: taking &str means the function accepts a &String (via deref coercion), a &str literal, or a slice of either. Returning &str means no allocation. And the borrow checker guarantees the returned slice can't outlive the input:

rust
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();                 // ❌ E0502: cannot borrow `s` as mutable
println!("{word}");        //     because it is also borrowed as immutable

Without slices, word would be a stale index into a cleared string. Rust catches it.

Array/vector slices

rust
let v = vec![1, 2, 3, 4, 5];
let mid: &[i32] = &v[1..4];      // [2, 3, 4]

fn sum(xs: &[i32]) -> i32 {
    xs.iter().sum()
}

sum(&v);          // works for Vec
sum(&v[1..3]);    // works for a slice
sum(&[1, 2, 3]);  // works for an array

API rule of thumb

Take &str not &String; take &[T] not &Vec<T>. It costs nothing and doubles the set of callers who can use your function.

Mutable slices exist too:

rust
fn double_all(xs: &mut [i32]) {
    for x in xs.iter_mut() { *x *= 2; }
}

let mut v = vec![1, 2, 3];
double_all(&mut v);
assert_eq!(v, vec![2, 4, 6]);

And split_at_mut gives you two disjoint mutable slices at once — proof that the "one mutable borrow" rule is about disjointness, not about counting:

rust
let mut v = [1, 2, 3, 4];
let (left, right) = v.split_at_mut(2);
left[0] = 10;
right[0] = 30;

Slices, and why &str is everywhere

A slice is a borrowed view of part of a collection: where the view starts, and how many items it covers. It owns nothing.

rust
let s = String::from("hello world");
let hello = &s[0..5];     // &str — a view into s, nothing copied

This explains the type you have been seeing since module 01. String is owned, growable text. &str is a borrowed view of text — which might be part of a String, or might be a literal baked into your executable ("hello" is a &str).

The practical rule that follows is one of the most useful in the language:

rust
fn greet(name: &str)    { }   // ✅ accepts &String, &str and literals alike
fn greet(name: String)  { }   // ✗ forces every caller to give up ownership
fn greet(name: &String) { }   // ✗ needlessly narrow — rejects plain literals

Take &str in parameters; return String when the caller needs to keep it. You will apply that a hundred times before this course ends.

And because a slice borrows, the borrowing rules apply: the compiler will not let the underlying String be modified or dropped while a slice of it is alive — for exactly the reason in the previous walkthrough.

Analogy — a bookmark, not a photocopy

A slice is a pair of bookmarks marking chapters 3 to 5 — no paper was copied, and the bookmarks are meaningless if the book is thrown away. That is precisely why the compiler will not let the book be dropped, or rewritten, while your bookmarks are still in it.

5.6 Debugging borrow errors: a checklist

When the borrow checker rejects your code, walk this list in order:

  1. Is it actually a lifetime problem? Does a reference outlive its referent? Restructure so the owner lives longer, or return an owned value.
  2. Are two borrows overlapping unnecessarily? Shorten one by introducing a let that copies the needed data out, or by adding a block { }.
  3. Do I need &mut where I wrote &? Check that the owner is also declared mut.
  4. Am I holding a borrow across a mutation of the container? (get then insert, index then push.) Compute first, mutate second.
  5. Do I need two mutable views of disjoint parts? Use split_at_mut, iter_mut, or indices instead of references.
  6. Is the design wrong? If two parts of the program truly need shared mutable access, you want Rc<RefCell<T>> or Arc<Mutex<T>> (modules 15 and 17), not a fight.
  7. Last resort while learning: .clone(). Note it with a // TODO: avoid clone.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
referenceAn access path to a value you do not own, written &value.
borrowTaking a reference. The owner keeps ownership throughout.
shared / immutable reference &TRead-only access. Many may exist at once.
mutable reference &mut TRead-write access. Only one may exist, and no shared ones alongside it.
dereference *Following a reference to reach the value itself. Often automatic.
slice &[T] / &strA borrowed view over part of a collection or string.
dangling referenceA reference to data that has been dropped. Rejected at compile time in Rust.
non-lexical lifetimes (NLL)The rule that a borrow ends at its last use rather than at the end of the block.
aliasingTwo paths reaching the same data. Safe when read-only; the reason for the one-writer rule when not.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0502]: cannot borrow as mutable ... also borrowed as immutableSomething is still reading the value when you tried to change it.Finish the read first — often just move the println! above the mutation, or wrap the read in its own block.
error[E0499]: cannot borrow as mutable more than onceTwo mutable references alive at the same time.Restructure so the first is finished before the second starts. In loops, take the reference inside the loop body.
error[E0596]: cannot borrow as mutable, as it is not declared as mutableYou need &mut but the binding itself is not mut.Change let x to let mut x.
error[E0106]: missing lifetime specifierYou returned a reference and the compiler cannot tell what it borrows from.For now, return an owned String instead. Module 13 teaches the annotation properly.
error[E0597]: does not live long enoughA reference would outlive the data it points at.Move the data's declaration to an outer scope, or return an owned value.

Now make it stick: work through the drills for this module, then carry on to Module 06 — Structs & Methods.