Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 132 ยท Ownership and Borrowing

References and Borrowing

Learn Rust references and borrowing - &T and &mut T, the one-writer-or-many-readers rule, dereferencing, dangling references and the errors E0382, E0499, E0502 and E0505.

After Ownership you know that passing a String to a function moves it, and the caller loses it. That is rarely what you want. Most functions just need to look at a value, or change it a little, and then hand control back. For that, Rust has references: a reference lets code use a value without owning it. Creating a reference is called borrowing, and like a library book, you must give it back, and while someone has it, there are rules about what others may do.

This lesson introduces the two kinds of reference, &T and &mut T, the single rule behind the borrow checker (many readers or one writer), what dereferencing means, how Rust prevents dangling references, and the four compiler errors you will see most often while learning. The next lesson, The Borrow Checker in Practice, turns this into a toolbox for fixing those errors.

Shared references: &T

Put & in front of a value to create a reference to it. A function that takes &String borrows the string instead of consuming it:

Rust Borrowing with &

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

&essay creates a reference and passes it. The function can read through it, but does not own the string, so nothing is dropped when word_count returns, and essay is still valid in main. A reference is just a pointer on the machine level (8 bytes on a 64-bit system), with compile-time rules attached.

You can have as many shared references as you like at once, because nobody can change the value through them:

Rust Many readers at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Prefer &str and &[T] for parameters

In real code, the parameter above should be &str, not &String. A &String automatically converts to &str (a deref coercion), so a &str parameter accepts string literals, &String and slices of strings alike. The same applies to &[T] instead of &Vec<T>. This is a style rule you will see everywhere; Slices explains it in depth.

Mutable references: &mut T

A shared reference is read-only. To change a value through a reference you need a mutable reference, written &mut. Both the variable and the reference must say mut:

Rust Changing a value through &mut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Forgetting a mut is a common first error. If greeting were declared without mut, the compiler would say cannot borrow 'greeting' as mutable, as it is not declared as mutable (E0596) and suggest the fix.

The one rule

Here is the rule that the whole borrow checker enforces. At any moment, for any value, you may have either:

  • any number of shared references (&T), or
  • exactly one mutable reference (&mut T),

but never both at the same time. Put differently: aliasing XOR mutation. A value may be seen by many, or changed by one, but not both at once.

Why? Think about the bugs this prevents. If one part of the program holds a pointer into a vector while another part pushes into it, the vector may reallocate and leave the first pointer dangling. If two threads write to the same place without coordination, you get a data race. If a function is iterating a list while a callback removes items from it, you get skipped or repeated items. All of these come from "someone else changed it while I was looking", and Rust makes that impossible at compile time with zero runtime cost.

E0499: two mutable borrows

Rust Two &mut at the same time (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0499]: cannot borrow `text` as mutable more than once at a time
 --> main.rs:5:18
  |
4 |     let first = &mut text;
  |                 --------- first mutable borrow occurs here
5 |     let second = &mut text;
  |                  ^^^^^^^^^ second mutable borrow occurs here
6 |
7 |     first.push('!');
  |     ----- first borrow later used here

Read the three labels: where the first borrow began, where the second one conflicts, and where the first is used later. That last label is the key: the conflict only exists because first is still needed. Swap the order of the lines so first is finished before second starts, and the code compiles.

E0502: shared and mutable together

The most common version of the conflict is holding a reference to an item, then changing the collection:

Rust A shared borrow alive while mutating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> main.rs:5:5
  |
4 |     let first = &scores[0];
  |                  ------ immutable borrow occurs here
5 |     scores.push(40);
  |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 |     println!("first score: {first}");
  |                             ----- immutable borrow later used here

This is exactly the dangling-pointer scenario from above: push may allocate a bigger buffer and move all the elements, which would leave first pointing at freed memory. In C++ this compiles and sometimes crashes. In Rust it is stopped before the program runs.

There are two ways to fix it. Finish using first before pushing, or copy the value out instead of borrowing it:

Rust Two fixes for E0502

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first fix works because of non-lexical lifetimes: a borrow lasts only until its last use, not until the end of the block. That detail gets its own lesson, The Borrow Checker in Practice.

E0505: moving while borrowed

You also cannot move a value while a reference to it is still going to be used:

Rust Moving out from under a borrow (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0505]: cannot move out of `text` because it is borrowed

consume would drop the string, and view would point at nothing. Once more the compiler spots the use-after-free before it exists. The fix: pass &text (borrow) instead of moving, or clone the text for consume.

Together with E0382 (use after move, from the ownership lesson), these are the four errors you will meet again and again. Here is a quick map:

Error Plain meaning Typical fix
E0382 You used a value after it was moved Borrow it, or clone it, or restructure
E0499 Two &mut to the same thing are alive Finish with one first, or split the data
E0502 A & and a &mut are alive together Use the & up before mutating, or copy the value out
E0505 You moved a value while borrowed Borrow instead of moving, or end the borrow first

Dereferencing

A reference points to a value. To get to the value itself you dereference with *. You saw it in *n *= 2 above: n is a &mut i32, and *n is the i32 it points to.

Rust The * operator and auto-dereferencing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For method calls, Rust dereferences automatically as many times as needed (auto-deref), which is why you almost never write (*name_ref).len(). You do need an explicit * when you assign through a reference, or compare or do arithmetic with the number behind it where the types would otherwise not match. Comparing two references with == compares the values they point to (not the addresses), which is usually what you want.

References can never dangle

In C you can return a pointer to a local variable, and the function's stack frame then disappears underneath it. In Rust a reference is guaranteed to point to a live value, and the compiler checks it:

Rust Returning a reference to a local (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TEXT
error[E0106]: missing lifetime specifier
 --> main.rs:1:23
  |
1 | fn make_greeting() -> &String {
  |                       ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
help: instead, you are more likely to want to return an owned value

As the last hint says, you most likely want to return an owned value. That is the answer: return an owned value, so ownership moves to the caller:

Rust
fn make_greeting() -> String {
    String::from("hello")
}

The 'static hint and the phrase "lifetime specifier" belong to the next big topic: every reference has a lifetime, the span of code in which it is valid, and the compiler compares it against the lifetime of the thing it points to. Most of the time lifetimes are inferred, and you never see them. When they matter, Lifetimes explains the syntax.

Borrowing in practice: parameter choice

When you design a function, the parameter type says what the function does with the argument:

Parameter Meaning Caller
s: &str, v: &[T] "I only read it" Keeps the value and may keep using it
s: &mut String, v: &mut Vec<T> "I will change it in place" Keeps ownership; value is changed on return
s: String, v: Vec<T> "I take it over (store it, consume it, or return it)" Gives it up

Start with the weakest need. Read-only borrowing is the default; use &mut when the function's job is to modify; take ownership when the function needs to keep the data (storing it in a struct) or turn it into something else.

A related design: a function that has to give back something derived from its input, such as the first word of a string, can return a reference into the input, as long as the compiler can tell how long the result lives. That is the subject of Slices.

Rust Returning a borrowed piece of the input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Here the output reference is tied to the input by the compiler's lifetime elision rules (one input reference means the output borrows from it). The value sentence cannot be changed or dropped while word is alive; otherwise word would dangle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which combination of references to the same value is allowed at the same time?

    Any number of shared references can coexist, but a &mut must be the only reference in use. 'Many readers or one writer.'
  2. 2. What does the following program do?

    let mut v = vec![1]; let first = &v[0]; v.push(2); println!("{first}");

    first is a shared borrow still used after v.push(2) needs a mutable borrow. push could reallocate the vector and leave first dangling, so the compiler rejects it.
  3. 3. Why is fn f() -> &String { let s = String::new(); &s } rejected?

    s is dropped at the end of f, so the reference would dangle. Return the String by value instead.
  4. 4. Given let r = &mut x; where x is an i32, how do you add one to the number x holds, through r?

    r is a reference. Use the dereference operator * to reach the integer behind it: *r += 1.
  5. 5. Which parameter type is the best choice for a function that only needs to read text?

    &str accepts string literals, &String (by deref coercion) and string slices, and it expresses read-only access.

Summary

  • A reference lets code use a value without owning it. &T is a shared (read-only) reference; &mut T is a mutable one, and both the binding and the reference must be declared mut.
  • The rule: at any moment you can have many &T or exactly one &mut T, never both. It prevents iterator invalidation, data races and dangling pointers at compile time.
  • * dereferences a reference; method calls and field access auto-dereference.
  • References can never dangle: returning a reference to a local variable is rejected (E0106), so return owned values instead.
  • Typical errors: E0382 (use after move), E0499 (two &mut), E0502 (& with &mut), E0505 (move while borrowed), and the fixes are usually to end one borrow earlier, copy a small value out, or clone.
  • Prefer &str and &[T] for read-only parameters; use &mut to modify in place; take ownership only when you must keep or consume the value.

Next: The Borrow Checker in Practice