In this lesson, you will learn how to use the 'static lifetime to identify data that remains valid for the entire duration of your program.
What is the 'static Lifetime?
Up until now, you have worked with references that live for a specific, often short, scope—like inside a function or a loop. However, some data is special. It is hard-coded into your program's binary and exists from the moment the program starts until it exits. In Rust, we represent this duration with the 'static lifetime.
The Most Common Example: String Literals
The most frequent place you encounter 'static is with string literals. When you write a message directly into your code, like let message: &str = "Hello, world!";, that string is stored directly in the program’s read-only memory.
Because the program is running the whole time that memory is accessible, message has a 'static lifetime. Rust knows that if you point to that string, the data will never be dropped or cleared while the program is running. You can technically annotate it like this:
let message: &'static str = "I live forever!";
Why does this matter?
The borrow checker uses lifetimes to ensure that you never have a "dangling pointer"—a reference to data that has already been cleaned up. If you have a function that expects a reference, but you pass it data that might disappear, the borrow checker will stop you.
If a function requires a 'static reference, it is essentially saying: "I need this data to be available for the entire program execution, because I might store it somewhere globally or use it in a way where I can't track exactly when it should be dropped."
By marking a reference as 'static, you are promising the compiler that the data will be valid for the program's entire life. This is a very strong guarantee, and because it is so restrictive, you usually only use it for data that is truly permanent.
Key Takeaway: The 'static lifetime signals that a reference is guaranteed to remain valid for the entire duration of the program, commonly seen with hard-coded string literals.