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

Borrowing from Option Enums

Access values within options using references without taking ownership.

In this lesson, you will learn how to inspect the contents of an Option without consuming it, allowing you to keep using the original variable afterward.

The Problem with Ownership

When you have an Option<T>, the most common methods like .unwrap() or pattern matching without references will attempt to "take" the value out of the enum. If you try this, you move the value out of the Option, leaving it empty (or invalidating the owner). If you wanted to keep using that Option later in your code, you would be blocked by the compiler.

Borrowing with .as_ref()

To solve this, we use the .as_ref() method. This method transforms an Option<T> into an Option<&T>. By doing this, you are effectively saying: "I don't want to take ownership of the inner value; I just want to look at it."

Consider this example:

fn main() {
    let my_name = Some(String::from("Ferris"));

    // We use .as_ref() to peek at the String without moving it
    match my_name.as_ref() {
        Some(name) => println!("Hello, {}!", name),
        None => println!("No name found."),
    }

    // Because we only borrowed, my_name is still available here!
    println!("I still have access to: {:?}", my_name);
}

Why This Matters

If we had tried to match on my_name directly without .as_ref(), the match block would have attempted to move the String out of the Option. By using .as_ref(), the match arm name becomes a reference (&String) instead of an owned String.

This is incredibly useful when you are working with configuration options, cached data, or any scenario where you need to check if a value exists and inspect it, but you aren't ready to destroy the container holding it. You are borrowing the inner contents, leaving the outer Option safely intact for future use.

Key Takeaway: Use .as_ref() on an Option when you need to inspect the inner value through a reference, ensuring you don't accidentally move the data and lose access to your variable.