Backend Development2025-12-24 07:47

How to define global variables in Rust

独孤影
独孤影
Author

As the title suggests, how do you define global variables in Rust?

In Rust, global variables cannot be modified at runtime. Rust global variables are static global variables, defined using the keyword static, as follows:

static mut count: usize = 0;

pub fn init_config(file_path: &str) {
    count = count + 1;
}

The compiler will tell you that modifying count is unsafe.

➜  las git:(feature/self-update-with-watcher-fork) ✗ cargo build
   Compiling las v0.1.1 (/root/code/las)
error[E0133]: use of mutable static is unsafe and requires unsafe function or block
  --> src/config/cfg.rs:35:13
   |
35 |     count = count + 1;
   |             ^^^^^ use of mutable static
   |
   = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior

error[E0133]: use of mutable static is unsafe and requires unsafe function or block
  --> src/config/cfg.rs:35:5
   |
35 |     count = count + 1;
   |     ^^^^^^^^^^^^^^^^^ use of mutable static
   |
   = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior

For more information about this error, try `rustc --explain E0133`.
error: could not compile `las` (bin "las") due to 2 previous errors
266

Comments (0)

Login to comment

Login Now

Loading comments...