I am trying to create a mutable static variable in Rust.
Note that this question is different to this:
In this case I am attempting to solve the problem without the use of other libraries, such as lazy static.
I succeeded in doing such a thing, but the compiler complained at the final step because what I had written was not thread-safe.
Since I am only working with a single thread, this is ok, but requires the use of unsafe Rust.
Rather than give in and use unsafe
I wanted to resolve this properly with a Mutex.
However I have not attempted any multithread Rust code before, and so unsurprisingly my attempt did not work.
My attempt does not work because I am attempting to return a reference to some local variable, which does not exist after the function returns.
I am also not that familiar with lifetime parameters, having not had to use them before, either.
But I don't know how to proceed from here.
Here's what I have so far.
struct Object {
field: i64
}
struct GlobalStruct {
}
impl GlobalStruct {
fn get() -> &'static mut Object {
static object_mutex: std::sync::Mutex<Option<Object>> = std::sync::Mutex::new(None);
let maybe_locked_mutex = object_mutex.lock();
match maybe_locked_mutex {
Ok(mut locked_mutex) => {
let &mut object = locked_mutex.as_mut().unwrap();
&mut object
}
Err(exception) => {
panic!("help");
}
}
}
}
fn main() {
let object = GlobalStruct::get();
}