I have a mutable global state used in my application instance, it is created during runtime; then I need to access the global state in another static struct (it's required to be static so I can't pass params from top down), which just needs an immutable global state reference. The global state doesn't implement Copy or Clone.
I was trying to create a global reference:
struct GlobalState;
struct Application;
static mut GLOB: Option<&GlobalState> = None;
// also use atomic bool to track, of course; for simplicity here
fn set_glob_singleton(glob: &'static GlobalState) {
unsafe {
GLOB = Some(glob);
}
}
impl GlobalState {
fn new() -> Self { Self }
}
impl Application {
pub fn run(&mut self) {
// set singleton?
// the actual global state init requires runtime data
let glob = GlobalState::new();
// ...
let g_singleton = Box::new(glob); // borrowed
set_glob_singleton(Box::leak(g_singleton));
// I need to use glob down there.
}
}
The problem is if I create a static reference, it borrows the glob
but I need to access and update it down that line.