Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Understanding Shared and Mutable References

Recommended resources

In our last lesson, we delved into Rust's ownership system, uncovering how it manages memory through strict rules about moving and copying data. We concluded by noting the inconvenience of functions always taking ownership, which forces us to pass ownership back and forth. Today, we'll explore Rust's elegant solution to this problem: borrowing.

This lesson introduces references, a concept that will feel familiar given your background in C and C++. However, you'll see that Rust elevates references by adding a set of compile-time rules enforced by the borrow checker. These rules eliminate entire categories of bugs, like dangling pointers and data races, that are common pitfalls in C++. By the end of this lesson, you will be able to use both shared (&) and mutable (&mut) references correctly, adhering to Rust's borrowing rules.

The Problem with Moving: A Quick Recap

As we saw, code like this is invalid because s1's ownership is moved into the calculate_length function:

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(s1);
    // println!("The length of '{}' is {}.", s1, len); // Error: value borrowed here after move
}

fn calculate_length(s: String) -> usize {
    s.len()
}

We could fix this by returning the String along with the length in a tuple, but that's cumbersome. There must be a better way to let a function use a value without consuming it.


Shared References: Borrowing Without Taking Ownership

The solution is to pass a reference to the value. A reference is like a pointer in that it’s an address we can follow to access data stored elsewhere. Unlike a pointer, a reference is guaranteed to point to a valid value of a particular type for the life of that reference.

We create a reference by using the ampersand (&) symbol. Let's see how this solves our problem.

Understanding Ownership in Rust

The video "Understanding Ownership in Rust," which we used in the last lesson, provides a clear explanation of this exact scenario.

Watch the segment from the start of references. It demonstrates how to change a function to take a reference (&String) instead of taking ownership of the String, a process called borrowing. Pay attention to how this fixes the compile error.

As the video shows, we can modify our code like this:

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1); // Pass a reference to s1
    println!("The length of '{}' is {}.", s1, len); // This now works!
}

// The function signature now takes a reference to a String
fn calculate_length(s: &String) -> usize {
    s.len()
}

Here, &s1 creates a reference that points to the value of s1 but does not own it. Because the function calculate_length only borrows s1, the ownership is not moved, and s1 is still valid after the function call.

These default references are immutable. Just as variables are immutable by default, so are references. If you try to modify a borrowed value through an immutable reference, the compiler will stop you.


Mutable References: Borrowing to Modify

What if we want to change the borrowed value? For this, Rust provides mutable references. You can create one using &mut.

There are two changes you need to make:

  1. The variable being borrowed must be declared as mut.
  2. You must create a mutable reference using &mut and accept it in the function with &mut Type.
fn main() {
    let mut s = String::from("hello"); // s must be mutable

    change(&mut s); // Pass a mutable reference

    println!("{}", s); // Prints "hello, world"
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}

This pattern is powerful because it allows functions to modify data they don't own, but it comes with a major restriction that forms the cornerstone of Rust's safety guarantees.

Rust Course for Beginners - Lesson 9 - References and Borrowing - Tutorial Rust lang rustlang

The video "References and Borrowing" by Federico Terzi gives a practical walkthrough of creating both shared and mutable references.

Watch the first two sections, covering shared references and then mutable references. This will solidify your understanding of the syntax.


The Rules of Borrowing

The "brutally strict" compiler you may have heard about is, in large part, the borrow checker. It enforces a simple set of rules that prevent data races and other memory unsafety bugs at compile time.

From your C++ experience, you know that a data race can occur when:

  • Two or more pointers access the same data at the same time.
  • At least one of the pointers is being used to write to the data.
  • There's no mechanism being used to synchronize access to the data.

Rust's borrowing rules make this entire class of bugs impossible in safe code.

The rules are as follows:

  1. At any given time, you can have either one mutable reference or any number of immutable references.
  2. References must always be valid (they cannot outlive the data they refer to).

Let's break these down.

Rule 1: One Writer OR Multiple Readers

This rule is the key to preventing data races. You can have many "readers" (immutable references) because they don't change the data. But as soon as you introduce a "writer" (a mutable reference), you cannot have any other references, mutable or immutable.

The techbuddies.io article frames this perfectly for someone with your background.

Rust for C++ Developers: Master Ownership and Borrowing Fast - techbuddies.io

This article is tailored for C++ developers and provides an excellent bridge to Rust's concepts.

Read the section titled "Aliasing and Mutability". It directly connects Rust's borrowing rule to the problem of data races and contrasts it with the conventions used in C++.

Let's see the compiler enforce this. This code is fine, as we have multiple immutable references:

let s = String::from("hello");

let r1 = &s;
let r2 = &s;

println!("{} and {}", r1, r2); // Works

But this code will fail to compile because we can't have a mutable reference while immutable ones exist:

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

let r1 = &s; // immutable borrow
let r2 = &mut s; // ERROR: mutable borrow

// println!("{} and {}", r1, r2);

The error message is explicit: cannot borrow 's' as mutable because it is also borrowed as immutable.

This image provides a great mental model for the two states:

This diagram illustrates the two borrowing scenarios. On the left, a shared reference (`&`) is created, and the original owner remains accessible for reading. On the right, a mutable reference (`&mut`) is created, which makes the original owner inaccessible to prevent data races.

The scope of a reference lasts from where it is introduced to the point where it is last used. This is an important subtlety. The compiler is smart enough to see when a reference's lifetime ends, allowing another borrow to occur.

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

let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2); // Last use of r1 and r2 is here.
// r1 and r2 go out of scope.

let r3 = &mut s; // This is now okay, because r1 and r2 are no longer in use.
println!("{}", r3);

Rule 2: No Dangling References

In C++, it's all too easy to create a dangling pointer—a pointer that refers to a memory location that has been freed. Trying to use it leads to undefined behavior.

// C++ example of a dangling pointer
std::string* dangle() {
    std::string s = "hello";
    return &s; // Returning a pointer to a local variable!
}

int main() {
    std::string* p = dangle();
    // `p` is now a dangling pointer. Using it is undefined behavior.
}

Rust's borrow checker completely eliminates this problem. The compiler ensures that data never goes out of scope before all references to it have gone out of scope.

Let's read the official explanation.

References and Borrowing - The Rust Programming Language

This chapter from the Rust book provides a deep dive into the mechanics of the borrow checker.

First, quickly read the introduction to aliasing and mutation to formalize the problem. Next, read the section on permission violations to see how the compiler catches errors. Then, read about mutable references and how they prevent aliasing by making the borrowed value temporarily unusable. Finally, read the section on lifetimes. It explains how Rust prevents dangling references by checking that data outlives its references.

If we try to write the same dangling pointer logic in Rust, the compiler will refuse with a clear error about lifetimes.

// fn dangle() -> &String { // dangle returns a reference to a String
//     let s = String::from("hello"); // s is a new String
//     &s // we return a reference to the String, s
// } // Here, s goes out of scope, and is dropped. Its memory is gone.
  // Danger!

The compiler error will mention "missing lifetime specifier," telling you that it cannot prove that the returned reference will be valid. This is Rust's safety net in action, turning a potential runtime disaster into a compile-time error.


Conclusion

In this lesson, you've bridged the gap between Rust's ownership and its practical application. By using references, you can now write efficient code that accesses data without needing to move it, all while being protected by the compiler.

Here are the key takeaways:

  • References (&) let you borrow a value without taking ownership.
  • By default, references are immutable (&T). To modify the data, you need a mutable reference (&mut T).
  • The borrow checker enforces two crucial rules at compile time:
    1. You can have either one mutable reference or any number of immutable references to a value in a particular scope, but not both.
    2. A reference can never outlive the data it points to, which prevents dangling references.

Your experience with C++ pointers gives you a head start in understanding the what and why of these rules. Rust's innovation is to make the compiler enforce them, giving you performance and safety.

In our next lesson, we will use these concepts of ownership and borrowing to build our own custom data types with structs and enums. You'll see how these constructs own data and how we can interact with them safely using the rules we've learned today.