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

Static Lifetimes

Handle data that persists for the entire duration of the program execution.

In this lesson, you will learn how to handle data that is intended to live for the entire duration of your program’s execution using the 'static lifetime.

The Concept of "Forever"

Up until now, we have dealt with variables that live on the stack or the heap and are cleaned up as soon as they go out of scope. But what if you have a piece of data, like a configuration string or a hardcoded error message, that you want to be available at any time, from anywhere in your program, until the moment the program exits?

In Rust, we represent this "forever" duration with the special lifetime marker 'static.

Hardcoded Data

The most common place you see this is with string literals. When you write let message = "Hello, Rust!";, the string "Hello, Rust!" is stored directly inside your program's binary. Because it is baked into the executable itself, it doesn't need to be allocated or deallocated at runtime. Its lifetime is 'static because it is valid for the entire life of the program.

You can explicitly label a reference as static like this:

fn main() {
    // The type of this variable is &'static str
    let greeting: &'static str = "Hello, world!";
    
    print_message(greeting);
}

fn print_message(msg: &'static str) {
    println!("{}", msg);
}

Why use 'static?

When you define a function that accepts a &'static str, you are telling the compiler: "I am not just asking for any reference; I am specifically asking for data that is guaranteed to be valid for the entire duration of this program."

This is incredibly powerful for safety. If the compiler knows the data will never be destroyed or deallocated before the program ends, it doesn't have to worry about dangling pointers or memory corruption. You are essentially promising the Borrow Checker that this data is permanent, and in return, the compiler allows you to use it anywhere without worrying about scope boundaries.

Key Takeaway: A 'static lifetime indicates that a reference is guaranteed to be valid for the entire duration of the program, such as data embedded directly into your binary.