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

Referencing Local vs Global Memory

Understand the lifetime differences between stack-allocated objects and static memory.

In this lesson, you will learn how the lifetime of a reference depends on where the data it points to actually lives in your computer's memory.

The Two Homes of Data

In Rust, every piece of data has a "home." Most of the variables you create inside a function live on the stack. When that function finishes, the stack frame is popped, and the data is destroyed. If you create a reference to that local data and try to return it, the compiler will stop you because the reference would point to a "ghost"—memory that no longer holds your data.

In contrast, global memory (often called static memory) lives for the entire duration of your program. Because this memory is baked into the binary itself, it is never cleaned up until the program exits.

Static References

When you want a reference to live forever, you use the 'static lifetime. This tells the compiler: "I guarantee this data will exist for the whole program."

fn get_local_string() -> &str {
    let message = String::from("Hello!");
    &message // ERROR: `message` dropped here, cannot return reference
}

fn get_global_string() -> &'static str {
    // This string literal lives in the binary's data section
    "Hello, I am global!" 
}

In the first example, message is local. It is born when the function starts and dies when it ends. You cannot return a reference to it because that reference would be invalid the moment the function returns.

In the second example, the string literal "Hello, I am global!" is stored in the read-only section of your executable. Because it is part of the program itself, it is always available. You can safely pass around a &'static str because the borrow checker knows it will never become invalid.

When you are designing your code, always ask: "Does this data belong to a specific function execution, or does it represent a constant value that should exist as long as the application is running?" Choosing between local scope and the static lifetime is the secret to avoiding those pesky "borrowed value does not live long enough" errors.

Key Takeaway: Local memory is temporary and tied to a function's scope, while global memory persists for the entire program duration, allowing for the 'static lifetime.