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

Passing References to Functions

Implement borrow-by-reference in function signatures to allow non-destructive data inspection.

Passing References to Functions

In this lesson, you will learn how to pass data to functions without transferring ownership, allowing your code to inspect values while keeping them safe for future use.

The Problem with Ownership

So far, you’ve learned that when you pass a variable to a function, Rust usually performs a "move," meaning the function takes full control of that data. Once the function finishes, the data is dropped, and you can no longer use your original variable. This is often inconvenient—what if you just want to look at a piece of data without destroying it?

Borrowing via References

Instead of passing the value itself, we can pass a reference. Think of a reference like a pointer to the data rather than the data itself. In a function signature, we indicate this by placing an ampersand (&) before the type. This tells Rust, "I am only borrowing this value; I don't own it, and I won't destroy it."

Consider this example where we check the length of a String:

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

    // We pass a reference (&) to the function
    print_length(&my_message);

    // Because we only borrowed it, we can still use my_message here!
    println!("Still here: {}", my_message);
}

fn print_length(message: &String) {
    println!("The length is: {}", message.len());
}

Why This Matters

When print_length receives &String, it has "read-only" access. It can call methods like .len() to inspect the data, but it cannot move or change the string. Because the function doesn't take ownership, the original my_message remains valid in main after the function call returns. This pattern is essential for writing efficient, non-destructive code, as it avoids unnecessary data duplication and allows multiple parts of your program to inspect the same information simultaneously.

Key Takeaway: By adding an & to a function parameter, you create a "borrowed" reference that allows the function to inspect data without taking ownership, ensuring your original variable remains available for use.