#Global mutable variable

27 messages · Page 1 of 1 (latest)

silk lantern
#

How can I create an global mutable variable?

undone needle
#

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

silk lantern
undone needle
#

you can call .lock() on the mutex to access the value

#

rustup update to get the latest compiler which supports calling new here

silk lantern
# undone needle `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    
undone needle
#

ah, the new function isn't const

#

can you make it a const fn new?

#

on the config

silk lantern
#

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
    }
undone needle
#

yeah that can't be const

#

you can use the once_cell crate

brittle cargoBOT
#

Single assignment cells and lazy values.

Version

1.13.1

Downloads

68 907 107

undone needle
#

they have an example for global mutable data

silk lantern
#

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?

undone needle
#

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

silk lantern
silk lantern
undone needle
#

yeah, you need the once_cell

silk lantern
#

In what case could this unwrap lead to a crash?

undone needle
#

if the last thread that had the lock panicked