use std::sync::Once;
struct Store;
impl Store {
fn new() -> Store {
Store {
manifest: RwLock::new(/* ... */), // @note: RwLock does not implement Clone
}
}
fn save(&mut self) {
// ...
}
}
Failing code:
static mut store: Option<Store> = None;
static INIT: Once = Once::new();
unsafe {
INIT.call_once(|| {
store = Some(Store::new());
});
store.unwrap().save(); // Error: cannot move out of static item `store`
}
The error is straightforward, yet this is something I desperately need to accomplish because Store::new()
does a ton of computationally expensive work under the hood.
I'm asking for the seemingly impossible: declare a static variable of type Store
and initialize it at runtime – given that new
cannot be static
due to absolutely critical interior mutability that occurs within that function. Additionally, RwLock
is a requirement and cannot be cloned. Dare I even ask whether this can be done in a way that is thread-safe?
There is no deferring the new
function call or its internal properties as subsequent function calls in my program (which are otherwise irrelevant) rely on it.
To help make the problem more clear, this is within the context of FFI. I do not have much control over the program's lifetime or the ability to manage this variable in a safer way. Although, I definitely want this Store
variable to live for the duration of the program's lifetime!
My question is conceptual. I am not by any means expecting this exact code to be slightly modified and suddenly compile. I'm asking a question here because I cannot wrap my head around how I can achieve what I want. I have tried several other methods... this is the best attempt I've made so far.