Ownership and Borrowing

Rust References and Borrowing

Let a function use a value without taking it: & to read, &mut to change.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • & and &mut
  • Borrowing in function calls
  • Many readers or one writer
Borrow → what it allows
length(&message)read only
add_exclamation(&mut message)can change it
let first = &messagemany readers are fine

Use a value without owning it

A reference lets code use a value without owning it. This is called borrowing. &value borrows for reading and &mut value borrows for changing.

length only reads the text, so it takes &str and message can still be used afterwards. add_exclamation needs &mut String to change it. Rust allows many readers at once or one writer, but never both, which rules out data races at compile time.

Key points

  1. &value borrows for reading.
  2. &mut value borrows for changing.
  3. Many readers or one writer, never both.

Runnable Rust example

Rust
Run code →
main.rs
fn length(text: &str) -> usize {
    text.len()
}

fn add_exclamation(text: &mut String) {
    text.push('!');
}

fn main() {
    let mut message = String::from("Borrow me");

    let size = length(&message); // immutable borrow
    println!("{message} has {size} bytes");

    add_exclamation(&mut message); // mutable borrow
    println!("{message}");

    let first = &message;
    let second = &message; // many readers are fine
    println!("{first} {second}");
}
Get a Run button for this example Result of running the code
Borrow me has 9 bytes
Borrow me!
Borrow me! Borrow me!

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Next: Slices →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges