The 'static lifetime in Rust
'static means the reference is valid for the whole program, not that the value never moves.
const TITLE: &'static str = "typestar";
static LANGS: [&str; 3] = ["rust", "sql", "css"];
fn remember<T: 'static + std::fmt::Debug>(value: T) {
println!("{:?} can be stored anywhere", value);
}
fn main() {
println!("{TITLE} knows {:?}", LANGS);
let owned = String::from("computed at run time");
let leaked: &'static str = Box::leak(owned.into_boxed_str());
println!("{leaked}");
remember(vec![1, 2, 3]);
}
How it works
- String literals are
&'static str, baked into the binary. - A
'staticbound on a generic means it owns its data. - Leaking a Box is the deliberate way to make one at run time.
Keywords and builtins used here
BoxStringTconstfnletmainrememberstaticstr
The run, in numbers
- Lines
- 16
- Characters to type
- 409
- Tokens
- 131
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 75 seconds.
Step 4 of 4 in Lifetime annotations, step 4 of 11 in Lifetimes & interior mutability.