OneBite.Dev - Coding blog in a bite size

Declare A Global Variable In Rust

Code snippet for how to Declare A Global Variable In Rust with sample and detail explanation

In the world of programming, managing global variables is important and necessary in many cases. In Rust language, global variables are static but they have unique properties to ensure safety. In this article, we will demonstrate how to declare a global variable in Rust.

Code snippet for Declaring a Global Variable in Rust

To declare a global variable, you need to use the keyword “static”. Here is a simple snippet:

static GLOBAL: i32 = 10;

fn main() {
    println!("The value of GLOBAL is: {}", GLOBAL);
}

In this code, “GLOBAL” is a global variable of type “i32” and has a value of “10”.

Code Explanation for Declaring a Global Variable in Rust

The declaration of a global variable in Rust is different from other languages. In Rust, global variables are read-only and thread-safe by default because they are immutable. Therefore, you can share them among many threads without problems.

Let’s break down the code snippet:

static GLOBAL: i32 = 10;

Here, static signifies that the variable is a global one. GLOBAL is the name of the variable, i32 denotes the data type, and 10 is the value assigned to the variable.

fn main() {
    println!("The value of GLOBAL is: {}", GLOBAL);
}

In the main function, the println! macro prints the value of GLOBAL to the console. Since GLOBAL is global, it can be accessed inside any other function including main.

Remember in Rust, the naming convention for global variables is to use entirely uppercase with underscores between words. This helps distinguish them from other variable types, making your code easier to read and understand.

To mutate a global variable in Rust, you would need to wrap the static within a Mutex or Atomic type for safety measures. That concept, however, falls outside of the scope of this simplistic introduction to declaring global variables in Rust.

rust