Declare Global Variables in Rust

Muhammad Adil May 11, 2022
  1. Global Variables in Rust
  2. Steps to Declare Global Variables in Rust
Declare Global Variables in Rust

Rust is a systems programming language that can create and use global variables. Global variables are values that are available to all parts of the program.

Global Variables in Rust

The Rust language offers two ways to declare global variables, const and static. The const keyword can declare immutable global variables, while the static keyword can be used to declare mutable global variables.

The let keyword is not permitted to be used in the global scope, so we can only use the keywords previously mentioned.

Global variables let us maintain a stack variable during runtime and hold even when allocating on the heap. There is still a pointer to the heap in the resulting machine code, saved on the stack.

Global variables are kept in the program’s data section. They have a set address that remains constant during computation.

As a result, the code segment can incorporate constant addresses and use no stack space.

Constant and Static Objects in Rust

Constants exist throughout a program’s existence. Constants in Rust, in particular, do not have a fixed memory location because they are functionally lined in each location where they are employed.

On the other hand, in static items, Rust offers a global variable kind of feature. Static objects are identical to constants, except they aren’t in line when used, which means that each value has a single instance stored at a specific position in memory.

Steps to Declare Global Variables in Rust

The following are the steps to define global variables in Rust:

  1. Create a file.
  2. Declare the variable using the const or static keywords.
  3. Define the variable.
  4. Compile your code.
  5. Run your code.

Example Code:

static SOME_INT: i32 = 100;
static SOME_STR: &'static str = "hello world";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 50,
    string: "global variable in rust",
};
fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);
}
struct MyStruct {
    number: i32,
    string: &'static str,
}

Click here to check the live demonstration of the code mentioned above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook