Course contentsShow
← Rust
Lesson 25 of 1,9101. Rust Fundamentals and ToolingFree lesson

The Role of Borrowing

Use references to access data without taking ownership of it, reducing unnecessary allocations.

In this lesson, you will learn how to access data without taking ownership of it, allowing you to use values throughout your program while keeping memory usage efficient.

The Problem with Ownership

Up until now, you’ve learned that in Rust, a variable "owns" its data. If you pass a variable to a function, that function takes ownership, and your original variable is no longer available. This is great for memory safety, but it's frustrating if you just want to look at a piece of data without destroying the original. If we had to clone or copy every single item every time we wanted to inspect it, our programs would be slow and memory-heavy.

Borrowing: The Solution

Borrowing allows you to grant temporary access to your data using references. Instead of handing over the "key" to the data, you hand over a reference, denoted by the & symbol. Think of this like letting a friend read a page in your notebook: they can see what is written, but they don't own the notebook, and they must give it back when they are done.

Because the function only borrows the data, the original variable remains valid after the function finishes.

fn main() {
    let greeting = String::from("Hello, Rust!");

    // We pass a reference (&greeting) instead of the whole string.
    print_length(&greeting);

    // The original greeting is still usable here!
    println!("Still have it: {}", greeting);
}

fn print_length(text: &String) {
    // We access the data without taking ownership.
    println!("The length is: {}", text.len());
}

Why This Matters

By using references, we avoid unnecessary allocations. Instead of creating a deep copy of a large string or vector every time we call a function, we simply point to the existing data in memory. This is the "secret sauce" of Rust’s performance—you get the safety of strict ownership rules, but you don't pay the performance penalty of constantly copying data to satisfy those rules.

Key Takeaway: Borrowing via references (&) allows you to access and use data without taking ownership, preventing unnecessary memory allocations while keeping your data safe and reusable.