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

Defining Immutable Borrowing

Create read-only references to existing data to allow shared access without taking ownership.

Defining Immutable Borrowing

In this lesson, you will learn how to grant read-only access to your data without transferring ownership, allowing multiple parts of your code to inspect the same value simultaneously.

The Problem with Ownership

Up until now, you have seen that when you pass a value to a function, the function typically takes ownership of it. Once the function finishes, the data is dropped (cleared from memory). But what if you have a String that you want to check the length of in one function, and then print in another? If the first function takes ownership, the second function will never get to see it.

Enter Immutable Borrowing

Instead of moving the data, Rust allows you to "borrow" it by creating a reference. A reference is like a pointer that is guaranteed to point to a valid piece of memory. By using the & symbol, you create an immutable borrow. This acts like a "read-only" permit: you can look at the data as much as you want, but you are not allowed to change it.

Consider this example:

fn main() {
    let book = String::from("The Rust Programming Language");

    // We pass a reference (&book) instead of the book itself.
    // The main function still owns the book!
    let length = calculate_length(&book);

    println!("The length of '{}' is {}.", book, length);
}

fn calculate_length(s: &String) -> usize {
    s.len() // We can read the string, but we can't modify it.
}

In the code above, calculate_length borrows the book. Because it is an immutable borrow, the compiler knows the data won't be modified while the function is running. This allows you to have as many immutable references to the same data as you need at the same time. Since the function doesn't own the string, the memory is not dropped when calculate_length ends.

This mechanism is the bedrock of Rust’s safety; it allows you to share data across your program safely, ensuring that no one can change the data behind your back while you are reading it.

Key Takeaway: Immutable borrowing creates a read-only reference (&T) that allows you to share data without giving up ownership, ensuring memory safety through restricted access.