乐闻世界logo
搜索文章和话题

How do you declare global variables in Rust?

1个答案

1

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 unsafe block because Rust cannot guarantee thread safety during access.
  • The type of a global variable must have the 'static lifetime, 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:

rust
static LANGUAGE: &str = "Rust"; static mut COUNTER: i32 = 0; fn main() { println!("Programming language: {}", LANGUAGE); unsafe { COUNTER += 1; println!("Counter: {}", COUNTER); } }

In this example:

  • LANGUAGE is an immutable global variable storing a string.
  • COUNTER is a mutable global variable that can be modified within an unsafe block.

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 回复

你的答案