Global variables in Rust are typically defined with a static lifetime and persist for the entire duration of program execution. To declare global variables in Rust, use the static keyword. Here are some key points to note:
- Global variables are immutable by default. If you need a mutable global variable, use
static mut, but this is generally discouraged due to potential data races. - Accessing mutable global variables must occur within an
unsafeblock because Rust cannot guarantee thread safety during access. - The type of a global variable must have the
'staticlifetime, meaning all referenced data must remain valid for the entire program runtime.
Example
Below is an example of declaring and using global variables in Rust:
ruststatic LANGUAGE: &str = "Rust"; static mut COUNTER: i32 = 0; fn main() { println!("Programming language: {}", LANGUAGE); unsafe { COUNTER += 1; println!("Counter: {}", COUNTER); } }
In this example:
LANGUAGEis an immutable global variable storing a string.COUNTERis a mutable global variable that can be modified within anunsafeblock.
This example demonstrates safe usage of global variables, particularly when handling mutability, and emphasizes the necessity of using unsafe to ensure developers are aware of potential risks.
2024年8月7日 15:27 回复