liveBook · Manning

Static lifetime

As explained in Learn Rust in a Month of Lunches

The static lifetime is a Rust lifetime that lasts for the entire duration of the program.

The static lifetime, written 'static, lasts for the entire program. A string literal such as "I live forever!" is stored directly in the binary, so its type is &'static str. A borrowed reference to a String usually has a shorter lifetime. section 10.1

Returning a string literal

A function may safely return a string literal: fn works() -> &'static str { "I live forever!" } It may not return a reference to a String created inside the function. That String disappears when the function ends, leaving an invalid reference. When the compiler suggests &'static str, it means the function must return data that really lives for the whole program; the annotation does not make temporary data live longer. section 10.2.1

Using 'static in a type is a restriction, not a lifetime-extending command. For example, a struct with name: &'static str accepts string literals but rejects a reference into a local String. Use a named lifetime such as struct City<'a> with name: &'a str when the reference only needs to live as long as the struct. section 10.2.2

Keep these practical distinctions in mind:

  • Use &'static str for data known to remain available for the entire program, especially string literals. section 10.1
  • Do not use 'static merely to silence a borrowing error; choose an owned String or an appropriate shorter lifetime instead. section 10.2.1 section 10.2.2
  • Regular spawned threads require captured items to have a 'static lifetime, while scoped threads avoid that requirement when their scope eventually ends. section 12.6

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains storage duration, compiler restrictions, function returns, and struct fields, but defers broader lifetime inference.
Examples
Uses string-literal returns, failing local references, compiler diagnostics, and City structs with static or named lifetimes.
What it assumes
Starts from references, String values, and string literals before introducing lifetime annotations and thread requirements.
What you can do after
Diagnose lifetime errors and choose between &'static str, owned String, and a named lifetime parameter.
How it connects
Connects static lifetime with string literals, borrowed references, ownership, lifetime annotations, generics, traits, and threads.

Also explained in

Compare how 2 books explain static lifetime →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.