Course contentsShow
← Rust
Lesson 63 of 1,9101. Rust Fundamentals and ToolingFree lesson

Static Lifetimes and Globals

Use static storage to hold data that persists for the entire program execution.

In this lesson, you will learn how to use the 'static lifetime and global variables to ensure data persists for the entire duration of your program.

Understanding the 'static Lifetime

So far, you’ve dealt with data that lives inside functions or structs, which gets cleaned up when it goes out of scope. In Rust, the 'static lifetime is a special guarantee: it tells the compiler that a piece of data will remain valid for the entire execution of the program.

The most common example is a string literal. When you write let message: &str = "Hello!";, the string "Hello!" is baked directly into your program's binary. It exists the moment the program starts and only disappears when the program exits. Because of this, the type of that reference is actually &'static str.

Creating Global Variables

Sometimes you need a piece of data that is accessible from anywhere in your code, like a configuration setting or a constant value. We use the static keyword to declare these.

static APP_NAME: &str = "My Rust App";

fn print_app_name() {
    println!("Welcome to {}", APP_NAME);
}

fn main() {
    print_app_name();
}

When you define a static variable:

  1. It must have an explicit type: Unlike let variables, you cannot rely on type inference here.
  2. It must be initialized: You must provide a value immediately.
  3. It has a fixed memory address: Because it lives for the whole program, the compiler knows exactly where it will sit in memory.

A Note on Safety

You might be tempted to use globals for everything because they are "always there," but be careful! Globals are easy to access but hard to track. If you find yourself needing to change the value of a global, you will quickly run into complex ownership rules. For now, treat static variables as read-only constants that help you avoid passing the same configuration data through every single function in your application.

Key Takeaway: The 'static lifetime ensures data exists for the entire life of your program, and static variables allow you to define globally accessible data that lives in a fixed memory location.