expression

Mutable static access and safer shared state

A mutable static has program-wide access risks, including reentrancy and conflicting accesses. Edition 2024 denies references to static mut by default. Prefer an immutable static with an atomic or lock. This counter needs no unsafe block; relaxed ordering is sufficient for this independent counter, not for publishing unrelated data. Expected stdout (not executed): 1 Common mistake: Creating a reference to static mut or assuming an unsafe block prevents races.

Formal Syntax & Structure

rust syntaxrust
static COUNTER: AtomicUsize = AtomicUsize::new(0);

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::sync::atomic::{AtomicUsize, Ordering};    static COUNTER: AtomicUsize = AtomicUsize::new(0);    COUNTER.fetch_add(1, Ordering::Relaxed);    println!("{}", COUNTER.load(Ordering::Relaxed));}
Rust Reference