RRust By Example
advancedUnsafe

Mutable Static Variables

Access and modify mutable static variables.

Mutable Static Variables

Access and modify mutable static variables.

Difficulty

Advanced

Code

rust
static mut COUNTER: u32 = 0;

unsafe fn increment() {
    COUNTER += 1;
}

unsafe fn get_counter() -> u32 {
    COUNTER
}

fn main() {
    unsafe {
        increment();
        increment();
        increment();
        println!("counter: {}", get_counter());
    }

    // global static (immutable)
    static MAX: u32 = 100;
    println!("max: {}", MAX);
}

Explanation

Mutable statics require unsafe. Use atomics instead.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the unsafe category to build a complete understanding of this topic.

More Unsafe Examples