Declaring global variables in Rust requires the use of the static keyword. Global variables in Rust are immutable by default and have a static lifetime, meaning they persist for the entire duration of the program. If you need a global variable to be mutable, you can use static mut, but this is strongly discouraged as it can lead to data races and other thread-safety issues unless you properly synchronize access.
Here is an example of declaring and using global variables in Rust:
rust// Declare an immutable global variable static LANGUAGE: &str = "Rust"; // Declare a mutable global variable static mut COUNTER: i32 = 0; fn main() { println!("Programming language: {}", LANGUAGE); // Must be performed within an unsafe block when using mutable global variables unsafe { COUNTER += 1; println!("Counter: {}", COUNTER); } }
In this example, we define an immutable global variable LANGUAGE and a mutable global variable COUNTER. LANGUAGE can be safely read anywhere because it is immutable. COUNTER is marked as mut and unsafe, meaning you must operate within an unsafe block when modifying or reading it. This is because Rust cannot guarantee thread-safety for access to mutable static variables.
While using global variables is sometimes necessary, it is generally better to avoid them, especially mutable ones, as they can make program behavior unpredictable and increase the complexity of debugging and maintenance. Ideally, consider alternative approaches such as using configuration files, environment variables, or passing parameters to avoid global state.