Static

A 'static lifetime is the longest possible lifetime, and lasts for
the lifetime of the running program. A 'static lifetime may also be
coerced to a shorter lifetime. There are two ways to make a variable
with 'static lifetime, and both are stored in the read-only memory
of the binary:

  • Make a constant with the static declaration.
  • Make a string literal which has type: &'static str.

See the following example for a display of each method:

  1. // Make a constant with `'static` lifetime.
  2. static NUM: i32 = 18;
  3. // Returns a reference to `NUM` where its `'static`
  4. // lifetime is coerced to that of the input argument.
  5. fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
  6. &NUM
  7. }
  8. fn main() {
  9. {
  10. // Make a `string` literal and print it:
  11. let static_string = "I'm in read-only memory";
  12. println!("static_string: {}", static_string);
  13. // When `static_string` goes out of scope, the reference
  14. // can no longer be used, but the data remains in the binary.
  15. }
  16. {
  17. // Make an integer to use for `coerce_static`:
  18. let lifetime_num = 9;
  19. // Coerce `NUM` to lifetime of `lifetime_num`:
  20. let coerced_static = coerce_static(&lifetime_num);
  21. println!("coerced_static: {}", coerced_static);
  22. }
  23. println!("NUM: {} stays accessible!", NUM);
  24. }

See also:

'static constants