The Static Lifetime
'static marks data that sticks around for the entire life of the program, never disappearing early.In this page:
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
fn main() {
let literal: &'static str = "I live for the whole program";
println!("{}", literal);
}
Login to try C/C++/Java/PHP code in the editor
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
static GREETING: &str = "Hello from a static variable";
fn main() {
println!("{}", GREETING);
}
Login to try C/C++/Java/PHP code in the editor
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
fn print_forever<T: std::fmt::Display + 'static>(value: T) {
println!("{}", value);
}
fn main() {
print_forever(String::from("owned, so it qualifies as 'static"));
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let owned_instead_of_static = String::from("Prefer owning data over forcing 'static");
println!("{}", owned_instead_of_static);
}
Login to try C/C++/Java/PHP code in the editor
- Overusing
'staticas a quick fix to silence a lifetime error, when it may not actually reflect the real relationship needed. - Assuming every string literal needs an explicit
'staticannotation -- they already have it implicitly. - Confusing
'staticdata with data that simply lives 'a long time' -- it specifically means valid for the entire program duration.
'staticis a special lifetime meaning the reference is valid for the entire duration of the program.- String literals have the type
&'static strautomatically, since they are embedded directly in the compiled binary. 'staticshould be used deliberately, not as a generic workaround for lifetime errors.- Data can be made
'staticby 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: