Access mutable statics in Rust by declaring them with `static mut` and wrapping all reads or writes in an `unsafe` block.
You access mutable statics in Rust by declaring them with static mut and reading or writing them inside an unsafe block.
static mut COUNTER: u32 = 0;
fn main() {
unsafe {
COUNTER += 1;
println!("{COUNTER}");
}
}
This pattern is unsafe because it bypasses Rust's borrow checker, allowing data races if accessed from multiple threads without synchronization.
A mutable static is a global variable that can change, but Rust blocks direct access to prevent crashes from multiple threads changing it at once. You must explicitly mark the access as unsafe to tell the compiler you are taking responsibility for thread safety. Think of it like a shared whiteboard in a busy office; you can write on it, but you must ensure no one else is writing at the same time to avoid messy results.