FerrousPath

Level 1 · Foundations· Lesson 5 of 10 · 25 min

References and borrowing

Using a value without owning it — shared and mutable references, the aliasing rule, and slices.

Borrowing instead of moving

A reference lets you refer to a value without taking ownership of it. Creating one is called borrowing.

fn length(s: &String) -> usize {
    s.len()
} // s is a reference; nothing is dropped here

fn main() {
    let s = String::from("hello");
    let n = length(&s); // lend s to the function
    println!("{s} has {n} bytes"); // s is still ours
}

&s creates a reference; &String is its type. The function borrows the string, reads it, and the borrow ends when the function returns.

Shared and mutable references

References come in two kinds.

Written Can read Can write How many at once
Shared &T yes no any number
Mutable (exclusive) &mut T yes yes exactly one
fn add_exclamation(s: &mut String) {
    s.push('!');
}

fn main() {
    let mut s = String::from("hello");
    add_exclamation(&mut s);
    add_exclamation(&mut s);
    println!("{s}");
}

Three things must line up: the variable is mut, the call site says &mut, and the parameter type is &mut String. Mutation is never a surprise to the reader.

The rule: aliasing XOR mutation

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.

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;
    let r2 = &s;        // fine: many readers
    let w = &mut s;     // ❌ error[E0502]: cannot borrow `s` as mutable
                        //    because it is also borrowed as immutable
    println!("{r1} {r2} {w}");
}

Why so strict? Because “someone changes data while someone else is looking at it” is the root of an enormous class of bugs. Here is a classic, which in C++ compiles and corrupts memory:

fn main() {
    let mut v = vec![1, 2, 3];
    let first = &v[0];  // points into v's heap buffer
    v.push(4);          // ❌ may reallocate the buffer → `first` would dangle
    println!("{first}");
}

The compiler does not know about vectors specifically. It only knows push needs &mut v while first is a live & into v — and that is enough to catch it. The same rule, applied across threads, is what prevents data races.

Borrows end at their last use

A reference’s scope lasts until the last place it is used, not until the closing brace. This compiles:

fn main() {
    let mut s = String::from("hello");

    let r1 = &s;
    println!("{r1}");   // last use of r1 — its borrow ends here

    let w = &mut s;     // fine now
    w.push_str(", world");
    println!("{w}");
}

So the fix for many borrow errors is simply to reorder: finish reading, then start writing.

No dangling references

A reference can never outlive what it points to.

fn dangle() -> &String { // ❌ error[E0106]: missing lifetime specifier
    let s = String::from("hello");
    &s
} // s is dropped here, so the reference would point at freed memory

fn main() {
    let r = dangle();
    println!("{r}");
}

The fix is to return the String itself and move ownership out.

Slices

A slice is a reference to a contiguous run of elements: a pointer plus a length. &str is a slice of UTF-8 text; &[T] is a slice of any element type.

fn first_word(s: &str) -> &str {
    match s.find(' ') {
        Some(i) => &s[..i],
        None => s,
    }
}

fn sum(xs: &[i32]) -> i32 {
    let mut total = 0;
    for x in xs {
        total += x;
    }
    total
}

fn main() {
    let sentence = String::from("hello wide world");
    let word = first_word(&sentence);
    println!("{word}");

    let numbers = [10, 20, 30, 40, 50];
    println!("{} {}", sum(&numbers), sum(&numbers[1..4]));
}

Two idioms to adopt now:

  • Take &str rather than &String in parameters. A &String converts to &str automatically, and &str also accepts string literals.
  • Take &[T] rather than &Vec<T>. It accepts vectors, arrays, and parts of either.

Because word borrows from sentence, the compiler will not let you clear or modify sentence while word is still in use. The slice cannot go stale.

Exercises

  1. Write fn largest(xs: &[i32]) -> i32. (Assume the slice is non-empty.)
  2. Write fn make_plural(word: &mut String) that appends an s.
  3. This fails to compile. Explain why and fix it without clone: let mut v = vec![1, 2, 3]; let last = &v[2]; v.clear(); println!("{last}");
Solution to 3

last is a shared borrow into v that is still used after v.clear(), which needs a mutable borrow. Either print before clearing, or copy the element out — let last = v[2]; — which works because i32 is Copy and no borrow remains.

Check your understanding

Pick an answer to see the explanation.

  1. 1.How many mutable references to one value can be live at the same time?

  2. 2.Why does Rust reject a function that returns a reference to its own local variable?

  3. 3.What is the type of &s[0..5] when s is a String?

Key terms in this lesson

Finished the lesson and the exercises?