How to create a global, mutable singleton in Rust?
Hello, colleagues!\n\nI'm new to Rust and trying to implement a global configuration for my application. I need to be able to read and modify settings (e.g., logging level or file path) from anywhere in the code. In other languages, I would simply use a static variable, but in Rust it's more complicated.\n\nHere's what I tried:\n\n```rust\nstatic CONFIG: Config = Config { logging: false };\n\nstruct Config {\n logging: bool,\n}\n\nfn main() {\n CONFIG.logging = true; // Error: cannot assign to static immutable\n}\n```\n\nThe compiler complains that the static is immutable. I tried `static mut`, but it requires `unsafe`:\n\n```rust\nstatic mut CONFIG: Config = Config { logging: false };\n\nfn main() {\n unsafe {\n CONFIG.logging = true; // Works, but unsafe\n }\n```
No answers yet.
Log in to leave an answer