liveBook · Manning

Static mut

As explained in Rust in Action: Systems programming concepts and techniques

static mut declares a mutable Rust static variable with a program-wide lifetime and mutable access requiring unsafe handling.

Rust declares a mutable global variable with static mut. The variable remains available throughout the program, but reading or modifying it requires an unsafe block. section 12.6.1 section 12.12

Use the feature with these rules and cautions:

  • Declare the variable at global scope, conventionally using an uppercase name such as static mut SHUT_DOWN: bool = false;. section 12.6.1
  • Wrap both writes and reads in unsafe blocks, including a seemingly harmless comparison. section 12.6.1
  • Treat unsafe as a warning that safety is no longer automatically guaranteed, rather than as an indication of illegal code. section 3.4.1
  • Avoid global state when possible because shared mutable access can make code cluttered and can create race-condition risks. section 12.6.1 section 12.12

A global shutdown flag

A program can set SHUT_DOWN to a random Boolean inside an unsafe block, print a dot, and then read the flag inside another unsafe expression. The loop stops when the flag becomes true. This small program makes the access boundary visible while modeling a flag that a signal handler might set. section 12.6.1

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains declaration and unsafe reads and writes through complete toy programs, but stops short of detailed concurrency guarantees.
Examples
Uses shutdown flags, random Boolean updates, global error codes, file operations, and panic output as concrete demonstrations.
What it assumes
Assumes basic Rust declarations and functions, while introducing global scope, mutable statics, and unsafe access through examples.
What you can do after
Apply mutable statics in small Rust programs that use global flags or error state, while identifying why unsafe access demands caution.
How it connects
Connects mutable statics with global variables, unsafe blocks, signal handlers, interrupts, operating systems, and race conditions.

Also explained in

Compare how 2 books explain static mut →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.