#Global mutable variable
27 messages · Page 1 of 1 (latest)
first, don't use global mutable variables, they are usually very bad
but if you are still sure that you need one for whatever reasons, you should use a static with some kind of lock like a mutex
static UWU: Mutex<u8> = Mutex::new(5);
(as of the latest rust version, Mutex::new can be used here)
instead of creating global variables, passing references to the functions that need them is usually better
I created the variable, but how can I now access and change the data inside of it?
you can call .lock() on the mutex to access the value
rustup update to get the latest compiler which supports calling new here
Error after updating rustup and letting it recompile every cargo(I'm not sure how the packages are called):
error[E0015]: cannot call non-const fn `config::Config::new` in statics
--> src\main.rs:20:43
|
20 | static CONFIG: Mutex<Config> = Mutex::new(Config::new(CONFIG_PATH));
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: calls in statics are limited to constant functions, tuple structs and tuple variants
For more information about this error, try `rustc --explain E0015`.
error: could not compile `app` due to previous error
How can I do that?
pub fn new(file_path: &str) -> Config {
// Defualt config
let mut config = Config {
file_path: file_path.to_string(),
fullscreen: false,
receiver_url: "localhost:3000".to_string(),
};
// Load config from file (if exists) and overwrite all config values, that are inside the config
if Path::new(file_path).exists() {
let file = File::open(file_path).unwrap();
let reader = BufReader::new(file);
// Read the file line by line
for (_index, line) in reader.lines().enumerate() {
let line = line.unwrap();
let split = line.split(":");
let mut i = 0;
let mut key = "";
let mut value = String::from("");
for s in split {
if i == 0 {
key = s;
}else {
value.push_str(s);
if i > 1 {
value.push_str(":");
}
}
i += 1;
}
println!("Key: {}", key);
match key {
"fullscreen" => {
if value == "true" {
config.fullscreen = true;
} else if value == "false" {
config.fullscreen = false;
} else {
println!("Invalid value of fullscreen: {}", value);
}
},
"receiver_url" => {
config.receiver_url = value;
},
&_ => println!("Unknown key: {}", key)
};
}
}
config
}
they have an example for global mutable data
I have another idea. Couldn't I just return the default config and make a function for loading the config and calling that before using the config?
that's also possible
but config has things like Strings which can't be created in the static initializer
but
you should not use a global variable here
create the config in main and then pass it as function arguments
like &mut Config
I already though about that, the problem is it doesn't work for some reason while using tauri
Ok that doesn't work because if the strings
yeah, you need the once_cell
In what case could this unwrap lead to a crash?
if the last thread that had the lock panicked