A global variable is accessible across multiple parts of a program. In Rust, declare one with static at global scope; mutable globals use static mut and require unsafe access, even for reading. section 12.6.1
Global state can propagate information such as error codes or an urgent shutdown request, but it is notoriously error-prone. Rust’s unsafe requirement acts as a warning to avoid global state when possible. section 3.4.1 section 12.6.1
Rust global variables use a small set of conventions and restrictions:
- Declare mutable global state with static mut, commonly using an uppercase name such as ERROR or SHUT_DOWN. section 3.4.1 section 12.6.1
- Wrap reads and writes of mutable globals in unsafe blocks. section 12.6.1
- Use a global error code to inspect failures after operations such as reading or closing a file. section 3.4.1
Error propagation with a global variable
A program can set static mut ERROR: isize = 0 inside read, then check ERROR after the call and panic when it is nonzero. The same pattern can check close, although the shared state makes failures easy to mishandle. section 3.4.1
Shutdown flag
A loop can repeatedly assign a random Boolean to static mut SHUT_DOWN, print a dot, and stop when an unsafe read finds true. This models a signal handler requesting urgent shutdown. section 12.6.1
Listing 12.6 Accessing global variables (mutable statics) in Rust
1 use rand;
2
3 static mut SHUT_DOWN: bool = false;
4
5 fn main() {
6 loop {
7 unsafe { #1
8 SHUT_DOWN = rand::random(); #2
9 }
10 print!(".");
11
12 if unsafe { SHUT_DOWN } {
13 break
14 };
15 }
16 println!()
17 }
Inspect the complete loop showing declaration, unsafe mutation, unsafe reading, and termination through a mutable global. section 12.6.1











