How about "generic global variables"?

static mut is still very problematic when encapsulated by privacy. For starters, you need to enforce synchronization, since other parts of the application may launch additional threads that call into the encapsulating code (so you'd have unsynchronized mutation). Furthermore, even if only a single thread is involved, code using static mut is almost certainly not reentrant because it's UB to hold two &mut to the at overlapping times (see also https://github.com/rust-lang/rust/issues/53639).

Leaving static mut aside, this observation hits at the key problem I see with implementing generic statics:

Because we still (unfortunately) support the dylib crate type, there is not necessarily a single place where all monomorphizations are known, and as far as I know there's no cross platform way to merge duplicate statics at the linking stage. So we can't actually guarantee that there is precisely one FOO::<i32> that all code agrees on.


Note that it's possible (with some run time overhead) to use TypeId and Box<Any> to collect "one value per type" in a single static. See crates.io: Rust Package Registry for example, though I think that's unmaintained and I have not audited the implementation.

3 Likes