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;

4. // Returns a reference to `NUM` where its `'static`
5. // lifetime is coerced to that of the input argument.
6. fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
7. &NUM
8. }

10. fn main() {
11. {
12. // Make a `string` literal and print it:
13. let static_string = "I'm in read-only memory";
14. println!("static_string: {}", static_string);

16. // When `static_string` goes out of scope, the reference
17. // can no longer be used, but the data remains in the binary.
18. }

20. {
21. // Make an integer to use for `coerce_static`:
22. let lifetime_num = 9;

24. // Coerce `NUM` to lifetime of `lifetime_num`:
25. let coerced_static = coerce_static(&lifetime_num);

27. println!("coerced_static: {}", coerced_static);
28. }

30. println!("NUM: {} stays accessible!", NUM);
31. }

See also:

'static constants