TExcelTAD
Home › Rust › Rust Borrowing

Rust Borrowing

In the previous chapter, passing a String to a function moved it away for good. Most of the time you just want to let a function look at (or modify) a value and then keep using it yourself. That is what borrowing is for.

A reference is a pointer to a value that you do not own. Creating a reference is called borrowing. You write it with &.

Immutable references: &T

rust · try it yourself
fn count_vowels(text: &String) -> usize {
    text.chars().filter(|c| "aeiou".contains(*c)).count()
}

fn main() {
    let sentence = String::from("borrowing is cool");
    let n = count_vowels(&sentence); // lend it, don't give it away

    println!("'{}' has {} vowels", sentence, n); // still ours!
}
'borrowing is cool' has 6 vowels

&sentence creates a reference, and the parameter type &String says "I borrow a String". When count_vowels ends, the reference disappears but the String is untouched, because the function never owned it.

Tip: For text, it's even better to accept &str instead of &String. A &String automatically converts to &str, and then the function also accepts string literals.

Mutable references: &mut T

A plain reference only allows reading. To change a borrowed value, you need a mutable reference, written &mut. The original variable must itself be mut.

rust · try it yourself
fn add_exclamation(text: &mut String) {
    text.push_str("!!!");
}

fn double_all(numbers: &mut Vec<i32>) {
    for n in numbers.iter_mut() {
        *n *= 2;
    }
}

fn main() {
    let mut shout = String::from("Watch out");
    add_exclamation(&mut shout);
    println!("{}", shout);

    let mut values = vec![1, 2, 3];
    double_all(&mut values);
    println!("{:?}", values);
}
Watch out!!!
[2, 4, 6]

The * in *n *= 2 is the dereference operator: it means "the value that n points to".

The borrowing rules

Rust enforces two rules at compile time:

  1. At any moment you may have either any number of immutable references (&T) or exactly one mutable reference (&mut T) — never both.
  2. A reference must never outlive the value it points to.

Think of it like a document: many people may read it at the same time, or one person may edit it, but nobody should read it while it's being edited. These rules rule out data races and many "iterator invalidation" bugs before your program ever runs.

You have… You may also create…
nothing &T or &mut T
one or more &T more &T
one &mut T nothing else until it is no longer used

A rule violation

rust
fn main() {
    let mut score = String::from("10");
    let reader = &score;
    let writer = &mut score;
    writer.push('0');
    println!("{}", reader);
}
text
error[E0502]: cannot borrow `score` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:18
  |
3 |     let reader = &score;
  |                  ------ immutable borrow occurs here
4 |     let writer = &mut score;
  |                  ^^^^^^^^^^ mutable borrow occurs here
5 |     writer.push('0');
6 |     println!("{}", reader);
  |                    ------ immutable borrow later used here

Borrows end at their last use

A reference's borrow lasts only until the last place it is used, not necessarily until the end of the block. So the following is fine, because reader is finished before writer starts:

rust · try it yourself
fn main() {
    let mut score = String::from("10");

    let reader = &score;
    println!("Reading: {}", reader); // last use of reader

    let writer = &mut score; // OK: no active immutable borrows
    writer.push('0');
    println!("After writing: {}", score);
}
Reading: 10
After writing: 100

No dangling references

Rule 2 means you cannot return a reference to something that is about to be dropped:

rust
fn make_name() -> &String {
    let name = String::from("temp");
    &name // name is dropped when the function ends!
}
text
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:19
  |
1 | fn make_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

The fix is simply to return the owned String itself (-> String, returning name). Ownership moves to the caller and nothing dangles.

Slices are borrows too

A slice borrows part of a collection. &s[0..4] borrows some bytes of a string, &arr[1..3] borrows some elements of an array.

rust · try it yourself
fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(pos) => &text[..pos],
        None => text,
    }
}

fn main() {
    let title = String::from("Fearless concurrency in Rust");
    let primes = [2, 3, 5, 7, 11, 13];

    println!("First word: {}", first_word(&title));
    println!("Middle primes: {:?}", &primes[1..4]);
}
First word: Fearless
Middle primes: [3, 5, 7]

Test yourself

How do you pass s to a function without giving away ownership?

  1. f(s)
  2. f(&s)
  3. f(*s)
  4. f(s.move())

Which combination of borrows is allowed at the same time?

  1. Two &mut references
  2. One & and one &mut
  3. Three & references
  4. A &mut and a move

What is required to call grow(&mut v)?

  1. v must be declared with let mut
  2. v must be a constant
  3. v must be cloned first
  4. Nothing special