I am learning rust. I read an article about static
https://practice.rs/lifetime/static.html
The main idea is clear - static lifetime means that reference is live till the end of the program.
fn main(){
let message;
{
let words = get_message();
message = words;
}
println!("message: {}", message);
}
fn get_message() -> &'static str {
"hello"
}
But what is profit of the static in production code?
Could you please provide example from real (production code) of 'static usage?
The primary profits of the static lifetime are:
1Note that mutating a 'static
object is unsafe
, but this can be worked around by using Cell<T>
or other means.
The two most common examples of the static lifetime that I know of are:
'static
and are stored in the data segment.lazy_static
crate, which allows flexible initialization of 'static
objects, is used by thousands of other crates, many of which appear in production applications and frameworks, including Tower, Tokio, and even Cargo.