Background
I have been learning rust recently and my most recent project involves setting a global APP_STATE
that can then be accessed throughout the app. There are a few other globals as well.
Note: These variables pretty much need to be globals, otherwise I will have to pass them as arguments into every function and trait I have - which is not very elegant.
The Problem
The aforementioned globals are mutable, i.e they are represented like the following:
pub Struct AppState {
running: bool
suspended: bool
}
static mut APP_STATE = AppState {running: true, suspended:false}
To access these values, I must use unsafe
like so: (Ignore the logic of code itself, just an example)
pub unsafe fn create_app {
APP_STATE.running = true;
APP_STATE.suspended = false;
}
unsafe fn confirm_app_state_valid() {
if APP_STATE.running == APP_STATE.suspended { // equality on booleans is just the XNOR(Logical Bi-conditional) operator.
fatal("Fatal! App was both running and suspended at same time. Could not resolve. Crashed")
};
}
The Question
How can I change my code to
- remove the
unsafe
(I understand why havingunsafe
is needed for mutable statics - avoid race conditions). Note that my app uses concurrency and performance is critical(graphics).
I want to remove the unsafe or atleast reduce its usage - currently it encompasses the entire main loop.
- not have to pass state as an argument everywhere