FAQ - Help and questions

How do I port global variables and singletons to Rust?

#porting#globals#concurrencypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Rust has globals, but a mutable global must be safe to share between threads. Use an atomic for counters, OnceLock for a value set once, and a Mutex for the rest. A better port often removes the global and passes a context value, which also makes the code testable.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 codeRust
A counter or flag changed from many placesstatic 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 changesstatic X: Mutex<T> (or RwLock<T>)
A singleton object with methodsA struct that you create in main and pass by reference
src/main.rsrust
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);
}
text
0 1 0
requests 3 config default
0 1 0 requests 3

The 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#

  1. List every global in the old code, and for each one, write down who changes it and from which threads.
  2. For read-only data, move it into a struct created in main and pass &Config where it is used. Use OnceLock only where passing it would mean changing dozens of signatures.
  3. For counters, use atomics. For shared mutable data, wrap the data in the Mutex, so that the lock and the data cannot be separated.
  4. 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 mut because it looks like a C global. Every access needs unsafe, and two threads using it is a data race the compiler no longer checks.
  • Holding a MutexGuard across 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet