← Back to Rust Course | Chapter 12: Lifetimes | Lesson 5 of 6

The Static Lifetime

'static marks data that sticks around for the entire life of the program, never disappearing early.

String Literals Are Static

Every string literal in Rust source code automatically has the type &'static str, because it is embedded directly into the compiled binary and exists for the whole program's run.

Example: String Literals Are Static

markup
fn main() {
    let literal: &'static str = "I live for the whole program";
    println!("{}", literal);
}

Declaring a Static Variable

The static keyword declares a global value with a fixed memory location that lasts the entire program, distinct from a 'static reference but closely related in meaning.

Example: Declaring a Static Variable

markup
static GREETING: &str = "Hello from a static variable";

fn main() {
    println!("{}", GREETING);
}

When You Might See 'static in Signatures

A function requiring a 'static bound on a generic parameter is saying that the value must not contain any non-'static borrowed references, which is common for values stored long-term, like in another thread.

Example: When You Might See 'static in Signatures

markup
fn print_forever<T: std::fmt::Display + 'static>(value: T) {
    println!("{}", value);
}

fn main() {
    print_forever(String::from("owned, so it qualifies as 'static"));
}

Avoid Overusing 'static

Reaching for 'static to silence a lifetime error is usually a sign the actual borrow relationship should be expressed differently -- it should describe truly whole-program data, not be a generic escape hatch.

Example: Avoid Overusing 'static

markup
fn main() {
    let owned_instead_of_static = String::from("Prefer owning data over forcing 'static");
    println!("{}", owned_instead_of_static);
}
Common Mistakes
  1. Overusing 'static as a quick fix to silence a lifetime error, when it may not actually reflect the real relationship needed.
  2. Assuming every string literal needs an explicit 'static annotation -- they already have it implicitly.
  3. Confusing 'static data with data that simply lives 'a long time' -- it specifically means valid for the entire program duration.
Chapter Summary
  • 'static is a special lifetime meaning the reference is valid for the entire duration of the program.
  • String literals have the type &'static str automatically, since they are embedded directly in the compiled binary.
  • 'static should be used deliberately, not as a generic workaround for lifetime errors.
  • Data can be made 'static by leaking memory intentionally (rare) or by simply being a compile-time constant or literal.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.