Sub topic 10
'static: string literals and T: 'static
This chapter covers the 'static lifetime. It assumes you can read lifetime annotations on functions and structs, and that you know ownership, &T and &mut T, String versus &str, and basic generics and trait bounds.
The name 'static shows up in two different roles, and mixing them up causes most of the confusion:
&'static Tis a reference whose target is valid for the rest of the program.T: 'staticis a bound on a type. It says the type holds no borrow that could expire.
What 'static means
'static is the longest lifetime. A reference of type &'static T is valid until the program ends, so the borrow checker never needs to worry about the data behind it being freed.
The name does not mean "allocated statically" or "never dropped". It is only a statement about how long a borrow is valid. This chapter shows that most values satisfying a 'static bound are ordinary heap values that get dropped like any other.
String literals
The most common source of &'static references is a string literal. The compiler stores the text in the program binary, which is mapped into memory for the whole run. Because that data cannot be freed, the type of a literal is &'static str.
fn greeting() -> &'static str {
"hello"
}
fn main() {
let g = greeting();
println!("{g}");
}This function returns a reference without taking any input reference. Normally that would be an error, because the compiler would have nothing to tie the output lifetime to. Here the output is 'static, so no input is needed.
Other places where you get &'static data:
staticitems, such asstatic NAME: &str = "app";, live for the whole program.- Constant expressions can be promoted.
let r: &'static i32 = &42;compiles because the compiler places42in static memory. Box::leakdeliberately gives up ownership of heap data and returns a reference to it that is valid forever.
fn leak_name(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
let name = leak_name(String::from("runtime-built"));
println!("{name}");
}Box::leak never frees the memory. Use it for values that really do live for the whole program, such as configuration loaded once at startup. Calling it in a loop leaks memory on every iteration.
A struct field can also demand 'static data:
struct Config {
name: &'static str,
}
fn main() {
let c = Config { name: "service" };
println!("{}", c.name);
}This struct needs no lifetime parameter, but it can only hold literals and other static data. It cannot borrow from a local String. That is a good choice for constants and a bad one for general-purpose types.
The T: 'static bound
A bound T: 'static means: every lifetime that appears inside T outlives 'static, which in practice means it is 'static. So T contains no references except 'static ones.
Whether a type satisfies the bound depends on what it contains:
| Type | Satisfies `T: 'static`? | Reason |
|---|---|---|
| `i32`, `bool` | Yes | No references inside |
| `String`, `Vec<u8>` | Yes | Owns its data |
| `&'static str` | Yes | The reference is static |
| `&'a str` for a local `'a` | No | The borrow can expire |
| `Excerpt<'a>` with a non-static `'a` | No | It holds a short borrow |
| `Vec<&'static str>` | Yes | All inner references are static |
The key point is that an owned String satisfies T: 'static. The bound does not require the value to live forever. It requires that nothing inside the value can become invalid before the value is dropped. The value can be created at any time and dropped at any time.
use std::fmt::Debug;
fn print_it<T: Debug + 'static>(t: T) {
println!("{t:?}");
}
fn main() {
let s: &'static str = "literal";
print_it(s);
print_it(String::from("owned"));
// let local = String::from("borrowed");
// print_it(&local); // error: `local` does not live long enough
}If you uncomment the last two lines, &local has type &'a String for some 'a that ends when local is dropped. That lifetime is shorter than 'static, so the bound fails and the compiler reports E0597.
Where the bound appears
You will meet T: 'static in standard library APIs that let a value escape the code that created it.
Spawning threads
std::thread::spawn requires its closure to be 'static. The new thread may keep running after the function that spawned it returns, so the closure cannot hold borrows of that function's locals.
use std::thread;
fn main() {
let name = String::from("worker");
let handle = thread::spawn(move || {
println!("hello from {name}");
});
handle.join().unwrap();
}The move keyword transfers ownership of name into the closure, so the closure holds no borrow. Without move, the closure would borrow name, and the compiler reports that the closure may outlive the current function (E0373).
When the thread really does finish before the function returns, you do not need 'static at all. thread::scope guarantees that all spawned threads are joined before the scope ends, so the closures may borrow local data:
use std::thread;
fn main() {
let words = vec![String::from("a"), String::from("bb")];
let total = thread::scope(|s| {
let h = s.spawn(|| words.iter().map(|w| w.len()).sum::<usize>());
h.join().unwrap()
});
println!("{total}");
}Type erasure and trait objects
Box<dyn Any> requires 'static, because Any uses type identity and cannot reason about borrowed lifetimes. Many async runtimes also demand 'static futures for spawned tasks, for the same reason as threads.
Trait objects have a default bound too. In a return type or a struct field, Box<dyn Trait> means Box<dyn Trait + 'static>. That surprises people who return a boxed value built from a borrowed argument. The fix is to name the lifetime, as the chapter on trait objects shows:
use std::fmt::Debug;
fn boxed<'a>(s: &'a str) -> Box<dyn Debug + 'a> {
Box::new(s)
}
fn main() {
let text = String::from("borrowed");
let b = boxed(&text);
println!("{b:?}");
}Written as Box<dyn Debug> with no + 'a, this function fails to compile because &'a str is not 'static.
Common misunderstandings
"'static means the value lives forever." &'static T means the referent is never freed during the program. T: 'static only means the type has no short borrows. A String is 'static and is still dropped normally.
"T: 'static means T is a &'static reference." It does not. Owned types satisfy it. Only types holding non-static references fail.
"Adding 'static fixes lifetime errors." Usually it moves the error to the caller. If you change fn f(s: &str) to fn f(s: &'static str), callers can pass only literals and leaked data. Likewise, adding T: 'static to a generic function rules out every borrowed T.
Choosing a fix when 'static is demanded
When an API insists on 'static and you have a borrow, you have four realistic options:
- Move the data in. Use
moveclosures or pass owned values. - Clone the data and hand over the copy. This costs an allocation but is often the simplest answer.
- Share ownership with
Arc<T>, which is'staticwhenTis, and clone theArcfor each user. - Use a scoped API such as
thread::scope, which removes the need for'static.
Reach for Box::leak only when the data truly lives until program exit.
Summary
&'static Tis a reference valid for the whole program. String literals,staticitems and leaked boxes provide them.T: 'staticmeans the type contains no non-static borrows. Owned types satisfy it.- Threads,
Box<dyn Any>and defaultBox<dyn Trait>require'staticbecause the value may outlive its creator. - Prefer moving, cloning,
Arc, or scoped APIs over making borrowed data'static.
Exercise
Which of these types satisfy T: 'static: String, &'static str, Vec<&'static str>, and a &str borrowed from a local String?
Show answer
The first three satisfy it. String owns its data, &'static str holds a static reference, and Vec<&'static str> holds only static references. The &str borrowed from a local String does not, because its lifetime ends when the local is dropped.
Exercise
The following code fails to compile. Explain why and fix it without using 'static in any signature.
fn main() {
let data = vec![1, 2, 3];
let handle = std::thread::spawn(|| {
println!("{}", data.len());
});
handle.join().unwrap();
}
Show answer
The closure borrows data, but thread::spawn requires a 'static closure because the thread could outlive main's locals (E0373). Add move so the closure owns data: std::thread::spawn(move || { println!("{}", data.len()); }). Alternatively, use std::thread::scope and borrow data inside the scope.
Exercise
Why does fn boxed(s: &str) -> Box<dyn std::fmt::Debug> { Box::new(s) } fail, and what is the minimal signature change that fixes it?
Show answer
In a return type, Box<dyn Debug> defaults to Box<dyn Debug + 'static>, but s is a non-static borrow. Tie the object to the input lifetime: fn boxed<'a>(s: &'a str) -> Box<dyn std::fmt::Debug + 'a>, or with elision, fn boxed(s: &str) -> Box<dyn std::fmt::Debug + '_>.