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

Dereferencing Syntax and Operators

Apply the dereference operator to access values underlying pointers and references.

In this lesson, you will learn how to use the dereference operator to "look through" a reference and access the actual value stored in memory.

What is Dereferencing?

When you create a reference—like &x—you are creating a pointer, or an "address" that points to where the data lives. Sometimes, you don't want to work with the address; you want to get your hands on the value held at that address. To do this, we use the dereference operator, which is the asterisk (*).

Think of a reference as an envelope with a house address written on it. The reference tells you where the house is, but it isn't the house itself. Dereferencing is like opening the front door so you can interact with what is inside.

Using the * Operator

Consider this simple example where we have an integer and a reference to it:

fn main() {
    let my_number = 42;
    let my_reference = &my_number;

    // my_reference is a &i32 (a pointer)
    // *my_reference is an i32 (the value 42)

    if *my_reference == 42 {
        println!("We accessed the value: {}", *my_reference);
    }
}

In the code above, my_reference is a type &i32. If you tried to compare my_reference directly to the number 42, the compiler would stop you because a "pointer" is not the same thing as an "integer." By placing the * in front of my_reference, you tell Rust: "Don't look at the address; follow the address to the memory location and give me the value stored there."

Why does this matter?

Dereferencing is essential when you need to perform calculations or comparisons on the data "behind" the reference. While Rust is sometimes smart enough to automatically "look through" references in specific scenarios (a feature we will see later), understanding the * operator is the foundation for manual memory control. It allows you to bridge the gap between a pointer and the actual data you intended to use.

Key Takeaway: The asterisk (*) is the dereference operator, which acts as a key to unlock a reference and grant you direct access to the underlying data.