Skip to content

rust.global_mutable_state

Correctness High

Detects mutable global state that causes race conditions and testing difficulties.

Global mutable state:

  • Race conditions — Concurrent access bugs
  • Hard to test — State leaks between tests
  • Implicit coupling — Hidden dependencies
// ❌ Before (static mutable)
static mut COUNTER: i32 = 0;
fn increment() {
unsafe {
COUNTER += 1; // Data race!
}
}
// ✅ After (atomic or explicit state)
use std::sync::atomic::{AtomicI32, Ordering};
static COUNTER: AtomicI32 = AtomicI32::new(0);
fn increment() {
COUNTER.fetch_add(1, Ordering::SeqCst);
}
// Or pass state explicitly:
fn increment(counter: &AtomicI32) {
counter.fetch_add(1, Ordering::SeqCst);
}
  • static mut declarations
  • Global lazy_static without synchronization
  • Shared state without proper guards

Unfault can suggest atomic types or explicit state passing.