In Rust, &value borrows a value without taking ownership of it. While it is borrowed, you can create as many shared references &T as you like, or exactly one mutable reference &mut T — never both at once. With that rule the compiler rejects code that would change a value while someone is still reading it, and a separate check rejects references that would point at a value after its owner is gone.

I found moving ownership into a function and getting it back on every call tedious. Most functions only need to read or modify a value, and references are how they do that. I wanted to work out which uses of references the compiler rejects and why, and how slices, which point at part of a string, and reborrowing, which passes a mutable reference along again, actually behave. Every example below was compiled with rustc 1.94.1, edition 2021, and the ones that compile were run to check their output.

Function Arguments

With a parameter of type &String, the function only borrows the value. message is still usable after the call.

fn char_count(text: &String) -> usize {
    text.chars().count()
}

fn main() {
    let message = String::from("héllo");
    let count = char_count(&message);
    println!("{message} has {count} chars");
}
héllo has 5 chars

The parameter text goes out of scope when char_count returns, but text is a reference, so the string is not dropped. Its owner is still message in main. The caller writes &message too, so the call site itself shows that the function only borrows. A better parameter type for functions that only read a string comes up in the slices section.

A shared reference cannot modify the value. Appending to the borrowed string fails with E0596.

fn append_suffix(text: &String) {
    text.push_str(" world");
}
error[E0596]: cannot borrow `*text` as mutable, as it is behind a `&` reference
 --> mut_on_shared.rs:2:5
  |
2 |     text.push_str(" world");
  |     ^^^^ `text` is a `&` reference, so it cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
1 | fn append_suffix(text: &mut String) {
  |                         +++

Taking a mutable reference &mut String, as suggested, lets the function modify the value without taking ownership. A function that used to take the value, change it, and hand it back now needs no return value.

fn append_suffix(text: &mut String) {
    text.push_str(" world");
}

fn main() {
    let mut message = String::from("hello");
    append_suffix(&mut message);
    println!("{message}");
}
hello world

A mutable reference requires the original variable to be let mut, and the call site has to write &mut. Whether a function can modify its argument shows up in both the signature and the call.

Shared and Mutable References

Many shared references or one mutable reference — overlapping them is E0502, two mutable references is E0499Many &T: allowed (read only)namesr1: &namesr2: &namesOne &mut T: allowed (read and write)namesw: &mut names&T and &mut T at once: rejected (E0502)namesr: &namesw: &mut namesTwo &mut T at once: rejected (E0499)namesw1: &mut namesw2: &mut names

The compiler accepts the top two cases in the diagram. A value can have several shared references at the same time, or one mutable reference. A shared reference overlapping a mutable one produces E0502, and two mutable references produce E0499.

This code creates two mutable references and uses them in turn.

fn main() {
    let mut log = String::new();
    let writer_a = &mut log;
    let writer_b = &mut log;
    writer_a.push_str("a");
    writer_b.push_str("b");
}
error[E0499]: cannot borrow `log` as mutable more than once at a time
 --> e0499.rs:4:20
  |
3 |     let writer_a = &mut log;
  |                    -------- first mutable borrow occurs here
4 |     let writer_b = &mut log;
  |                    ^^^^^^^^ second mutable borrow occurs here
5 |     writer_a.push_str("a");
  |     -------- first borrow later used here

The third label, first borrow later used here, is the reason. writer_a is used again on line 5, so the first mutable borrow lasts until line 5 and overlaps the second one on line 4. Creating writer_b after writer_a is done compiles.

fn main() {
    let mut log = String::new();
    let writer_a = &mut log;
    writer_a.push_str("a");
    let writer_b = &mut log; // writer_a was last used by push_str above
    writer_b.push_str("b");
    println!("{log}");
}
ab

In most cases a borrow ends at the reference’s last use, not at the end of the variable’s scope. The lifetimes post covers how that region is computed and where the exceptions are.

Creating a mutable reference while a shared one is alive is E0502. The classic case is pushing onto a vector while iterating over it.

fn main() {
    let mut names = vec![String::from("alice"), String::from("bob")];
    for name in &names {
        if name.starts_with('a') {
            names.push(name.to_uppercase());
        }
    }
}
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
 --> e0502_loop.rs:5:13
  |
3 |     for name in &names {
  |                 ------
  |                 |
  |                 immutable borrow occurs here
  |                 immutable borrow later used here
4 |         if name.starts_with('a') {
5 |             names.push(name.to_uppercase());
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

The for loop borrows &names until iteration finishes. push may reallocate the vector’s buffer, which would leave the iterator and name pointing at freed memory. The compiler rejects that before the program ever runs.

The rule applies just the same to types that never reallocate. Reading an integer while it is mutably borrowed is also E0502.

fn main() {
    let mut count = 0;
    let counter = &mut count;
    println!("{count}");
    *counter += 1;
}
error[E0502]: cannot borrow `count` as immutable because it is also borrowed as mutable
 --> e0502_int.rs:4:16
  |
3 |     let counter = &mut count;
  |                   ---------- mutable borrow occurs here
4 |     println!("{count}");
  |                ^^^^^ immutable borrow occurs here
5 |     *counter += 1;
  |     ------------- mutable borrow later used here

*counter dereferences the reference to reach the value behind it. This program is single-threaded and would run fine. The compiler, however, does not look at the number of threads; it decides from how the value is borrowed. The Rust Programming Language lists three conditions for a data race: two or more pointers access the same data at the same time, at least one of them writes, and nothing synchronizes the access. With ordinary references, writing requires a mutable reference. While it is alive, no other reference exists. So a writing pointer and another pointer can never reach the same value at the same time. On a single thread this rule keeps a buffer from changing under an iterator; across threads it works together with the Send and Sync trait checks to prevent data races. Interior mutability types like Mutex, which allow modification through a shared reference, are out of scope here.

References to Local Values

A local String's buffer is freed when the function returns, so return the owned String instead of a referenceInside shout: upper owns the bufferupper: String"HI"If it returned a reference: after upper drops (E0515)returned &strfreed bufferReturning String: ownership moves to the callerreturned String"HI"

The shared/mutable rule covers a borrowed value changing. A value disappearing before the reference does is a separate check. A reference to a freed value is called a dangling reference.

A value created inside a function is dropped when the function returns. Returning a reference to it would hand the caller a reference to a freed buffer, so the compiler rejects the function at its definition.

fn shout(text: &str) -> &str {
    let upper = text.to_uppercase();
    &upper
}
error[E0515]: cannot return reference to local variable `upper`
 --> e0515.rs:3:5
  |
3 |     &upper
  |     ^^^^^^ returns a reference to data owned by the current function

to_uppercase allocates a new String, owned by the local variable upper. When shout returns, upper is dropped and its buffer freed. Through the lifetime elision rules, the return type &str promises something borrowed from the input text, but what the function actually returns points at a value that is about to be freed.

A newly created value is returned with its ownership.

fn shout(text: &str) -> String {
    text.to_uppercase()
}

fn main() {
    println!("{}", shout("hi"));
}
HI

Whether to return ownership or a reference depends on where the value comes from. Part of the data borrowed from an input can be returned as a reference. A value created inside the function has to be returned by ownership. What moves is the String value — pointer, length, and capacity — and the heap buffer is not copied.

A function with no input reference that returns a reference gets a different error. The compiler reports E0106, saying there is nothing for the return value to borrow from, and suggests either a 'static lifetime or returning an owned value, noting that 'static is uncommon.

fn default_name() -> &String {
    let name = String::from("guest");
    &name
}
error[E0106]: missing lifetime specifier
 --> e0106.rs:1:22
  |
1 | fn default_name() -> &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`
  |
1 | fn default_name() -> &'static String {
  |                       +++++++
help: instead, you are more likely to want to return an owned value
  |
1 - fn default_name() -> &String {
1 + fn default_name() -> String {
  |

Lifetime annotations, which record in a signature which input a returned reference comes from, are out of scope here.

Slices

&String is one pointer to the String; &str is a pointer into the heap buffer plus a length&line: &Stringptr8 bytesline: Stringptrlen 11cap 1124 bytesheap bufferGET␣/healthmethod: &strptrlen 316 bytes

A slice is a reference to part of a contiguous sequence. As the diagram shows, a string slice &str holds a start address inside the string data and a length. That differs from &String, which is a single pointer to the String value. Printing the sizes confirms it.

fn main() {
    let line = String::from("GET /health");
    let method: &str = &line[0..3];
    println!("{method}");
    println!("same buffer: {}", method.as_ptr() == line.as_ptr());
    println!("size_of::<&String>() = {}", std::mem::size_of::<&String>());
    println!("size_of::<&str>() = {}", std::mem::size_of::<&str>());
    println!("size_of::<&[i32]>() = {}", std::mem::size_of::<&[i32]>());
}
GET
same buffer: true
size_of::<&String>() = 8
size_of::<&str>() = 16
size_of::<&[i32]>() = 16

On a 64-bit target, &String is 8 bytes, while &str and &[i32] are 16 bytes: a pointer plus a length. method points at the first byte of the same buffer as line; nothing is copied.

For a function that only reads a string, I prefer &str over &String as the parameter type. A caller holding a String passes &line, and a string literal can be passed as is. The conversion from &String to &str is deref coercion.

fn first_word(text: &str) -> &str {
    text.split(' ').next().unwrap_or(text)
}

fn main() {
    let line = String::from("GET /health");
    let method = first_word(&line);
    println!("{method}");
    println!("{}", first_word("POST /login"));
}
GET
POST

A slice is a reference, so it follows the shared/mutable rule. Clearing the original string while a slice into it is alive is E0502.

// first_word is the same as above
fn main() {
    let mut line = String::from("GET /health");
    let method = first_word(&line);
    line.clear();
    println!("{method}");
}
error[E0502]: cannot borrow `line` as mutable because it is also borrowed as immutable
 --> slice_clear.rs:8:5
  |
7 |     let method = first_word(&line);
  |                             ----- immutable borrow occurs here
8 |     line.clear();
  |     ^^^^^^^^^^^^ mutable borrow occurs here
9 |     println!("{method}");
  |                ------ immutable borrow later used here

Had first_word returned the word’s position as an integer, this code would compile and leave a meaningless index after clear. Returning a slice keeps the link to the original as a borrow, which the compiler can check.

Part of an array or vector is borrowed as &[T]. A function taking &[i32] accepts a vector, a fixed-size array, or a range of either.

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

fn main() {
    let scores = vec![10, 20, 30];
    let fixed = [1, 2, 3, 4];
    println!("{} {} {}", total(&scores), total(&fixed), total(&scores[1..]));
}
60 10 50

Reborrowing

A shared reference &T is Copy, so passing it around leaves the original usable. A mutable reference &mut T is not Copy; copying it would create two mutable references to the same value. Yet a function that receives a mutable reference can pass it to another function twice, and it compiles.

fn append_item(items: &mut Vec<i32>, value: i32) {
    items.push(value);
}

fn fill(items: &mut Vec<i32>) {
    append_item(items, 1);
    append_item(items, 2);
}

fn main() {
    let mut items = Vec::new();
    fill(&mut items);
    println!("{items:?}");
}
[1, 2]
With a &mut parameter each call gets a temporary reborrow; with a generic T the mutable reference movesappend_item(items: &mut Vec<i32>, ..)itemsreborrowfn fill(items: &mut Vec<i32>) {append_item(items, 1);append_item(items, 2);}log_and_push<T>(target: T)itemsmovedfn fill(items: &mut Vec<i32>) {log_and_push(items);log_and_push(items);}E0382

append_item(items, 1) does not move items. When the parameter type is known to be &mut Vec<i32>, the compiler passes &mut *items — a fresh mutable borrow of the vector items points to. That reborrow ends when the append_item call returns, and the next line can use items again. The short bars in the top half of the diagram are the reborrow on each call; the bottom half is the generic parameter case that comes next.

A generic parameter T behaves differently. The compiler infers T as &mut Vec<i32> and passes items itself, so the mutable reference moves.

fn log_and_push<T: std::fmt::Debug>(target: T) {
    println!("{target:?}");
}

fn fill(items: &mut Vec<i32>) {
    log_and_push(items);
    log_and_push(items);
}
error[E0382]: use of moved value: `items`
 --> generic_move.rs:7:18
  |
5 | fn fill(items: &mut Vec<i32>) {
  |         ----- move occurs because `items` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
6 |     log_and_push(items);
  |                  ----- value moved here
7 |     log_and_push(items);
  |                  ^^^^^ value used here after move
  |
help: consider creating a fresh reborrow of `items` here
  |
6 |     log_and_push(&mut *items);
  |                  ++++++

The &mut *items in the help is the reborrow the compiler inserted earlier, written out by hand. For the same reason, an unannotated let alias = items; moves items, while let alias: &mut Vec<i32> = items; reborrows. I compiled both to check.

A reborrow follows the borrowing rules too. While the reborrowed reference is alive, the original mutable reference cannot be used to write.

fn fill(items: &mut Vec<i32>) {
    let alias = &mut *items;
    items.push(2);
    alias.push(1);
}
error[E0499]: cannot borrow `*items` as mutable more than once at a time
 --> reborrow_conflict.rs:3:5
  |
2 |     let alias = &mut *items;
  |                 ----------- first mutable borrow occurs here
3 |     items.push(2);
  |     ^^^^^ second mutable borrow occurs here
4 |     alias.push(1);
  |     ----- first borrow later used here

A reborrow does not copy the mutable reference. It makes the original unusable for a while and lends out a new mutable reference in the meantime. At any point there is only one path that can modify the value. That is why passing a &mut to other functions several times still keeps the one-mutable-reference rule intact.

Wrapping Up

A reference borrows a value without taking ownership. The rule of many shared references or one mutable reference rejects code that changes a borrowed value, and references that would outlive their owner are rejected separately. That leaves a return value as either a reference borrowed from an input or an owned value. Passing a mutable reference along several times compiles through reborrowing, yet only one path can modify the value at any point. Choosing between & and &mut on a parameter decides what a function can do with a value.

References