Course contentsShow
← Rust
Lesson 101 of 1,9102. The Ownership ModelFree lesson

Immutable Reference Semantics

Utilize read-only views into data without triggering expensive moves or copies.

In this lesson, you will learn how to inspect data without taking ownership of it by using immutable references.

Borrowing Without Taking

So far, you have learned that moving data can be expensive, especially when dealing with heap-allocated resources that aren't simple, stack-based integers. If you pass an object into a function, the function takes ownership, and your original scope loses access to it. This is inefficient if you simply want to "look" at the data to perform a calculation or print it.

To solve this, Rust provides Immutable Reference Semantics. Instead of transferring ownership, you create a "view" of the data. This is often called borrowing.

How It Works

You create an immutable reference by placing an ampersand (&) before the variable name. This tells the compiler: "I want to look at this data, but I promise not to change it." Because you don't own the data, Rust doesn't trigger a destructor when the function ends, avoiding the overhead of cleanup or complex memory moves.

Consider this example:

fn print_length(s: &String) {
    // We borrow 's' here. We can read it, but not move it.
    println!("The length is: {}", s.len());
}

fn main() {
    let my_string = String::from("Hello, Rust!");
    
    // We pass a reference, so 'my_string' stays in 'main'
    print_length(&my_string);
    
    // 'my_string' is still valid here!
    println!("Still have: {}", my_string);
}

By passing &my_string, we provide the function a read-only window into our memory. Since the function doesn't own the String, it cannot deallocate the heap memory associated with it. This allows multiple parts of your program to inspect the same piece of memory simultaneously without violating safety rules or wasting resources on unnecessary copies.

As long as the original owner (in this case, my_string) stays in scope, the immutable reference remains valid. Once the reference goes out of scope, the original owner continues to manage the resource as usual.

Key Takeaway: Immutable references allow you to share read-only access to data across your program without transferring ownership or incurring the cost of deep copying.