Course contentsShow
← Rust
Lesson 222 of 1,9103. Borrowing and ReferencesFree lesson

The Reborrowing Pattern

Create a temporary sub-borrow from an existing mutable reference to pass into a helper.

In this lesson, you will learn how to temporarily "split" or delegate a mutable reference to a helper function without losing access to the original reference.

The Problem: Moving the Reference

When you have a mutable reference (&mut T), it represents exclusive access to data. If you pass this reference directly to a function, Rust’s ownership rules might cause the original reference to be "moved" into that function. Once moved, you can no longer use the original reference in the scope where it was defined.

This is where the Reborrowing Pattern comes in.

Creating a Temporary Sub-Borrow

A reborrow allows you to create a new, temporary mutable reference from an existing one. This new reference acts as a proxy. Because it is a reborrow, it is strictly tied to the lifetime of the original reference. Once the function receiving the reborrow finishes, the "original" reference becomes usable again.

Consider this example:

fn update_value(val: &mut i32) {
    *val += 1;
}

fn main() {
    let mut number = 10;
    let ref_to_num = &mut number;

    // We reborrow 'ref_to_num' by passing it to the function.
    // The &mut * syntax explicitly creates a reborrow.
    update_value(&mut *ref_to_num);

    // Because we reborrowed, 'ref_to_num' is still valid here!
    *ref_to_num += 5;
    println!("{}", ref_to_num); // Prints 16
}

Why use &mut *?

By writing &mut *ref_to_num, you are effectively saying: "De-reference this mutable pointer to get the actual value, and immediately borrow that value again for this specific function call."

While Rust often does this automatically (a process called implicit reborrowing), explicitly using &mut * makes it clear to the reader that you are creating a temporary, restricted view of your reference rather than handing over the original reference entirely. This keeps your code clean and prevents the compiler from complaining that you’ve "moved" a value that you still need to use later in your main block.

Key Takeaway: The reborrowing pattern allows you to pass a mutable reference into a helper function while maintaining your original access by creating a temporary, shorter-lived sub-borrow.