Answer#
C has static and global variables, Java and C# have static fields and singleton classes, Python and JavaScript have module-level variables. Rust has static items too, but with a rule that follows from its thread safety: a static is reachable from every thread, so it must be safe to use from every thread. A plain static mut exists, but every use of it is unsafe, and you should avoid it in a port.
The table gives the usual replacement for each kind of global. The program below uses each of them, and then the alternative that removes the global. It was compiled and run with rustc 1.93.0.
| Old code | Rust |
|---|---|
| A counter or flag changed from many places | static X: AtomicU64 (or AtomicBool) |
| A value created once at start-up and then only read (configuration, a compiled regular expression) | static X: OnceLock<T> |
| A shared table or cache that changes | static X: Mutex<T> (or RwLock<T>) |
| A singleton object with methods | A struct that you create in main and pass by reference |
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
// C: static int counter; Java: private static final Config INSTANCE
static REQUESTS: AtomicU64 = AtomicU64::new(0);
static CONFIG: OnceLock<Config> = OnceLock::new();
static CACHE: Mutex<Option<HashMap<String, u32>>> = Mutex::new(None);
struct Config {
name: String,
}
fn config() -> &'static Config {
CONFIG.get_or_init(|| Config { name: "default".to_string() })
}
fn lookup(key: &str) -> u32 {
REQUESTS.fetch_add(1, Ordering::Relaxed);
let mut guard = CACHE.lock().unwrap();
let map = guard.get_or_insert_with(HashMap::new);
let next = map.len() as u32;
*map.entry(key.to_string()).or_insert(next)
}
// The version that is easier to test: no globals, the state is a value that is passed in.
struct App {
requests: u64,
cache: HashMap<String, u32>,
}
impl App {
fn lookup(&mut self, key: &str) -> u32 {
self.requests += 1;
let next = self.cache.len() as u32;
*self.cache.entry(key.to_string()).or_insert(next)
}
}
fn main() {
println!("{} {} {}", lookup("a"), lookup("b"), lookup("a"));
println!("requests {} config {}", REQUESTS.load(Ordering::Relaxed), config().name);
let mut app = App { requests: 0, cache: HashMap::new() };
println!("{} {} {} requests {}", app.lookup("x"), app.lookup("y"), app.lookup("x"), app.requests);
}0 1 0
requests 3 config default
0 1 0 requests 3The Mutex<Option<HashMap<..>>> is Option only because a static must be created by a const expression, and HashMap::new() is not one; the first call fills it. The second version, App, needs none of that. It is also the one you can test: each test creates its own App, while the global version shares state between tests that run in parallel.
How to do it#
- List every global in the old code, and for each one, write down who changes it and from which threads.
- For read-only data, move it into a struct created in
mainand pass&Configwhere it is used. UseOnceLockonly where passing it would mean changing dozens of signatures. - For counters, use atomics. For shared mutable data, wrap the data in the
Mutex, so that the lock and the data cannot be separated. - Lock for as short a time as you can, and never hold a lock while calling code that might lock again.
Common mistakes#
- Reaching for
static mutbecause it looks like a C global. Every access needsunsafe, and two threads using it is a data race the compiler no longer checks. - Holding a
MutexGuardacross a slow call (a network request). Other threads wait for all of it. - Porting a singleton as a global when the old code only needed one instance, not global access. A value passed down the call chain does the same job.
Related questions#
Why can't I write static CACHE: Mutex<HashMap<String, u32>> = Mutex::new(HashMap::new())?#
The compiler rejects it with error E0015, "cannot call non-const associated function HashMap::<String, u32>::new in statics", and suggests wrapping the value in std::sync::LazyLock (not tried here). Options that compiled with rustc 1.93.0: OnceLock<Mutex<HashMap<..>>> filled on first use, Option as above, or a BTreeMap, whose new is allowed in a static (static SORTED: Mutex<BTreeMap<String, u32>> = Mutex::new(BTreeMap::new());).
Is a thread-local variable a good replacement for a global?#
Only when each thread should have its own copy. thread_local! gives each thread a separate value, which is not what a shared counter or cache needs.
Sources#
- The Rust Book, "Unsafe Rust" (mutable static variables): https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html
std::sync::OnceLock: https://doc.rust-lang.org/std/sync/struct.OnceLock.htmlstd::sync::atomic: https://doc.rust-lang.org/std/sync/atomic/index.html