Global state, is this possible?

I generally don't use global state. However, when working with macros that are invoked in different modules, it can be convenient to use some form of global state in 1 module so that different modules can work with the same things (as opposed to passing around a structure or tuple). When I say global state, I would like it to be global at least to 1 module (I don't think it can be more global than that), it can be thread-local, it needs to be able to store arbitrary types of data.

So here's the question. If I maintain some sort of global state that has things of type T, can I have portions of code that do the following things.

  • call_a_function(&T)
  • call_a_function(T.clone())
  • T.do_something()

Basically, I need to be able to pass around references to them, and do stuff with them as if they were local variables in scope.

Is this possible?

You could make a lazy_static next to the macro and access it inside the macro?

As for “compile-time global state” you can look at this for inspiration, but it's a hack.

1 Like
pub static mut my_global: usize = 100;

unsafe fn needs_semaphore_or_atomics() {
    assert_eq!(my_global, 100);

fn main() {
    unsafe { needs_semaphore_or_atomics() }

This is the easy way to do it, but be warned that you will need some way to ensure there are no data races involved. You could wrap it in a mutex or something alike

I would advise against advertising static mut as an “easy way”. It should only be used in exceptional circumstances and, hopefully, will be deprecated entirely one day, as it breaks the usual aliasing semantics of mut. Using static mut without UB is pretty hard.

The easy way is to use an atomic or a lazy_static/once_cell, with optional Mutex, if one needs unique access.


I eat the nomicon for breakfast

It devours you inside-out.


... and from the ashes and fires of the dark abyss, I rise to hold the nomicon in these gleaming hands

... without darkness, light would not pervade. The nomicon is the way, the truth, and the darkness which lets God cast his highest light

1 Like

Guys, static mut is always a bad idea, just use lazy_static.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.