1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-05 09:07:29 +02:00
comprehensive-rust/src/unsafe/mutable-static-variables.md
Martin Geisler c4bc10e31d
Inline variables printed with println! and friends (#315)
The course follows the style of inlining variable names where possible
in `println!` statements.
2023-02-09 07:48:18 +01:00

767 B

Mutable Static Variables

It is safe to read an immutable static variable:

static HELLO_WORLD: &str = "Hello, world!";

fn main() {
    println!("HELLO_WORLD: {HELLO_WORLD}");
}

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

static mut COUNTER: u32 = 0;

fn add_to_counter(inc: u32) {
    unsafe { COUNTER += inc; }  // Potential data race!
}

fn main() {
    add_to_counter(42);

    unsafe { println!("COUNTER: {COUNTER}"); }  // Potential data race!
}

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.