skip to content

Static Bounds

&'static str is a borrow valid for the whole program, but T: 'static means only that T holds no short borrows. Interviewers check the difference, which thread::spawn depends on.

on this pageshow

questions

4

In Rust, what does the type `&'static str` promise, and why does every string literal have that type?

level: juniorimportance: must knowfreq 70%

answer

  1. valid for the rest of the run
  2. where the literal's bytes live
  3. a borrow of a local never qualifies
  4. static items have the static lifetime

basics

~20 s

A &'static str borrows string data that stays valid until the program ends. Literal bytes are compiled into the binary and never freed, so every literal has that type; a borrow of a local String never does.

solid answer

~40 s

`&'static str` is a shared reference to `str` data that is guaranteed valid from the moment you hold it until the program ends, so it can be stored anywhere and kept for as long as you like. A string literal such as `"parquet"` has exactly that type because its bytes are embedded in the compiled binary and are never deallocated. A `static` item's contents qualify too, since static items have the `'static` lifetime and are never dropped. A borrow of a local `String` does not, even one that lives until `main` returns: passing it where `&'static str` is required fails with E0597, `argument requires that ... is borrowed for 'static`. The usual fix is to store an owned `String`, not to demand `'static` from every caller.

code

rust · 18 lines
rust
static BUILTIN: [&str; 2] = ["csv", "json"];

struct Registry {
    names: Vec<&'static str>,
}

impl Registry {
    fn register(&mut self, name: &'static str) {
        self.names.push(name);
    }
}

fn main() {
    let mut reg = Registry { names: BUILTIN.to_vec() };
    reg.register("parquet"); // a literal is already &'static str
    let first: &'static str = BUILTIN[0];
    println!("{first} {:?}", reg.names);
}

go deeper

for a junior

Recall that a string literal has type &'static str because its bytes sit in the binary, and that 'static means valid until the program ends.

for a middle

Explain why borrowing a local String for a &'static str parameter fails with E0597 even when the String lives until main returns, and name the owned-String fix.

for a senior

Show judgment about API signatures: demanding &'static str from callers is a design smell unless the data really is compile-time or deliberately leaked; prefer owned storage.

for a principal

Treat 'static requirements as an API contract decision: they push allocation or leaking onto every caller, so reserve them for names and tables fixed at compile time or built once at startup.

## What the type says A **lifetime** in Rust is the region of the program during which a borrow is guaranteed to point at valid data. `'static` is a lifetime name reserved by the language itself: it covers the **entire remaining run of the program**. So `&'static str` reads as "a shared reference to UTF-8 string data that will never dangle, however long you keep it". That promise is what lets you put such a reference into long-lived places without any lifetime parameter: a field of a registry that lives for the whole process, a global table, a value handed to another thread. Because it is a shared reference, `&'static str` is also `Copy`: passing it to a function or storing it in two places copies only a pointer and a length, never the text. ## Why every string literal is `&'static str` When rustc compiles `"parquet"`, it places the bytes in the program's binary and gives the expression the type `&'static str`. The Rust Book puts it directly: the text of a string literal is stored in the binary, which is always available, so all string literals have the `'static` lifetime. Nothing ever allocates or frees those bytes at run time, so no borrow of them can dangle. The same reasoning covers **static items**. The Reference states that static items have the static lifetime, which outlives all others, and that static items do not call drop at the end of the program. A reference into a static is therefore `'static`, and in a `static` or `const` declaration an elided `&str` is implicitly `&'static str`. ## Where a `&'static str` can come from | Source | Example | Why it is `'static` | |---|---|---| | A string literal | `"parquet"` | bytes compiled into the binary | | A static item | `BUILTIN[0]` with `static BUILTIN: [&str; 2]` | the static lives for the whole program | | Constant promotion | `&LIMIT` where `LIMIT` is a `const` | the compiler promotes the constant value to a `'static` slot | | A deliberate leak | `Box::leak(s.into_boxed_str())` | the allocation is never freed | A borrow of a heap `String` you built at run time is never on this list unless you leak it on purpose. ## The plugin registry that rejects a config value Consider a registry of plugin names typed as `Vec<&'static str>`: ```rust fn register(&mut self, name: &'static str) { self.names.push(name); } ``` `reg.register("parquet")` compiles. Now read a name from configuration into a `String` and pass `&from_config`. rustc 1.99 reports: ```plaintext error[E0597]: `from_config` does not live long enough | argument requires that `from_config` is borrowed for `'static` 16 | } | - `from_config` dropped here while still borrowed ``` The surprise for many candidates is that `from_config` lives until the end of `main`. That is still not `'static`: the local is dropped when `main`'s body ends, and the type `&'static str` claims validity for the whole program. The compiler checks the claim against where the owner is dropped, not against how long the program happens to keep running. ## Choosing the fix 1. **Own the data.** Change the field to `Vec<String>` (or a borrowed-or-owned type, covered with clone-on-write) so runtime names are stored by value. This is the normal answer. 2. **Thread a lifetime parameter** through the registry if it really only lives as long as its source, which is the subject of structs holding references. 3. **Leak once, deliberately**, when the value truly must live for the rest of the process, such as names loaded once at startup. The Book adds a warning worth repeating in an interview: when an error message suggests adding `'static`, the real cause is usually a dangling reference or mismatched lifetimes, and the fix is to repair that, not to annotate `'static`. ## Common misreadings - **"It lives on the heap."** A literal's bytes are part of the binary; a `&'static str` is just a pointer and a length into them. - **"Lives until `main` returns, so it is `'static`."** A local is dropped at the end of `main`'s body; E0597 says so. - **"`'static` means declared with the `static` keyword."** Literals, promoted constants and leaked boxes all produce `'static` borrows without a `static` item. - **"The literal is copied at each use."** Each use evaluates to a reference to existing bytes; nothing is allocated. - **"`&'static str` and `String` are interchangeable."** A `String` owns a heap buffer and frees it when dropped; a `&'static str` owns nothing and frees nothing, which is exactly why it can be kept forever.

  • Why does `static BUILTIN: [&str; 2]` need no explicit `'static` on its element type?
    The Reference's const and static elision rule: reference types in `const` and `static` declarations get an implicit `'static` lifetime unless another one is written. So `[&str; 2]` there means `[&'static str; 2]`, and indexing it yields a `&'static str` you can store anywhere.
  • rustc's help suggests changing a parameter to `&'static str`. When is that the wrong fix?
    Almost always when the data is produced at run time. Requiring `&'static str` restricts callers to literals, statics and leaked allocations, so every caller holding a `String` hits E0597. The Book notes that such suggestions usually point at a dangling reference or a lifetime mismatch; fix that, or take an owned `String`.
  • Can a `static` item hold a `std::cell::Cell<u32>` hit counter?
    No. A static's type must implement `Sync`, because every thread can reach it, and `Cell<u32>` is not `Sync`; rustc 1.99 rejects it with E0277, `Cell<u32>` cannot be shared between threads safely. An atomic integer is the usual replacement, covered with atomics.

  • A &'static str points at heap memory that is freed when main returns.
  • A String that lives until the end of main can be lent out as &'static str.
  • Only values declared with the static keyword can have the 'static lifetime.
  • Adding 'static to a parameter is the standard fix for any lifetime error.
  • A string literal allocates a fresh copy of its text every time the line runs.
open as a page

Why does Rust's `std::thread::spawn` require a `'static` closure, and how do you fix E0373 when it borrows a local vector?

level: middleimportance: must knowfreq 66%

basics

~20 s

thread::spawn requires F: 'static because the new thread can outlive its caller, so a borrow of the caller's locals could dangle. Fix E0373 with move to hand owned data over, or move in an Arc clone to share it.

open as a page

In Rust, what does the bound `T: 'static` require of a type, and why does `String` satisfy it while `&'a str` does not?

level: middleimportance: must knowfreq 62%

basics

~20 s

T: 'static means the type holds no borrow shorter than 'static: it owns its data or borrows only 'static data. String owns its bytes; &'a str with a shorter 'a does not qualify. The value can still be dropped anytime.

open as a page

In a long-running Rust service, when is `Box::leak` an acceptable way to get a `&'static` reference, and what does it cost?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Box::leak safely turns a Box into a &'static mut by never freeing it. It suits data built once that must last the whole process, like startup config. Drop never runs, and leaking per request grows memory without bound.

open as a page