Mutable Static Variables

It is safe to read an immutable static variable:

  1. static HELLO_WORLD: &str = "Hello, world!";
  2. fn main() {
  3. println!("HELLO_WORLD: {HELLO_WORLD}");
  4. }

However, since data races can occur, it is unsafe to read and write mutable static variables:

  1. static mut COUNTER: u32 = 0;
  2. fn add_to_counter(inc: u32) {
  3. unsafe { COUNTER += inc; } // Potential data race!
  4. }
  5. fn main() {
  6. add_to_counter(42);
  7. unsafe { println!("COUNTER: {COUNTER}"); } // Potential data race!
  8. }

Using a mutable static is generally a bad idea, but there are some cases where it might make sense in low-level no_std code, such as implementing a heap allocator or working with some C APIs.