Search code examples
ruststatic

Static reference in Rust


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?


Solution

  • The primary profits of the static lifetime are:

    1. a guarantee that a reference will always be valid, which is sometimes useful in e.g. multi-threaded contexts1,
    2. allowing the compiler/linker to put data in the data segment of the executable (the same as literals and global/static variables in C/C++), which is very fast to load and uses a separate addressing space (which matters more for 32-bit architectures, where even with address extension each process is typically limited to a few GB of virtual memory),
    3. guaranteeing that memory allocations and de-allocations (aside from stack allocations) do not happen during runtime, which can be important for embedded applications or other situations where memory usage needs to be highly deterministic.

    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:

    1. As in your example, string literals! All string literals are automatically 'static and are stored in the data segment.
    2. the 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.