25.8 Mutable Global Variables
Global mutable variables in Rust are declared with static mut
. They are inherently unsafe because concurrent or multi-path write access can lead to data races.
#![allow(unused)] fn main() { static mut COUNTER: i32 = 0; fn increment() { unsafe { COUNTER += 1; } } }
It's best to minimize the use of mutable globals. When they are required, you should apply synchronization primitives to ensure safe, race-free access.