Can you use global variables in Rust? How to declare global state?
Hello! I've been writing in Rust for a couple of weeks and ran into a problem. I need to store application configuration and a request counter accessible from different modules. In C++ I would do it like this:
```rust
// My attempt (doesn't compile)
static COUNTER: i32 = 0;
static CONFIG: HashMap = HashMap::new();
fn increment() {
COUNTER += 1; // Error: cannot assign to immutable static
}
fn main() {
CONFIG.insert("host".to_string(), "localhost".to_string()); // Error
println!("{}", COUNTER);
}
```
The compiler complains about mutability and about `HashMap` it says something about `const fn` and allocations. I read that global variables in Rust are complicated, but how do you do shared settings then? I need:
1. A simple counter that can be incremented from different threads.
2. A co
No answers yet.
Log in to leave an answer