1

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?

mascai
  • 1,373
  • 1
  • 9
  • 30
  • 1
    It's commonly used for example for error messages wich are known at compilation time. It could be applied for any data for which you know the value and the size at compilation time and that you may use along the entire life of the program execution. – Peterrabbit Aug 13 '23 at 14:03
  • 1
    Are you asking _where `&'static` appears_, or _why is it useful when it appears_? – Chayim Friedman Aug 13 '23 at 14:16
  • Does this answer your question? [When is a static lifetime not appropriate?](https://stackoverflow.com/questions/66510485/when-is-a-static-lifetime-not-appropriate) – user2722968 Aug 13 '23 at 17:40
  • I'm unsure what you mean with *'profit'* - it's in many cases not a matter of taste, but of necessity. – Finomnis Aug 13 '23 at 20:19

1 Answers1

2

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.
bug
  • 143
  • 1
  • 9