banner
orion

orion

中国科学技术大学研究生;数据库内核开发工程师;生产力爱好者;

How to define and use global variables in Rust

Introduction#

Rust is a safe and efficient systems programming language. Its syntax is similar to C, but it excels in safety and concurrency. Defining and using global variables in Rust can help us share data within a program, improving code reusability and maintainability. In this article, we will introduce how to define and use global variables in Rust.

Defining Global Variables#

In Rust, defining global variables requires the use of the static keyword. There are two ways to define global variables:

Defining Immutable Global Variables#

static GLOBAL_VAR: i32 = 42;

In the code above, we define a global variable named GLOBAL_VAR, of type i32, with an initial value of 42. It is important to note that the defined global variable must specify a type. After defining an immutable global variable, we can read its value anywhere in the program.

Defining Mutable Global Variables#

static mut GLOBAL_VAR: i32 = 42;

In the code above, we use static mut to define a mutable global variable named GLOBAL_VAR, of type i32, with an initial value of 42. It is important to note that defining a mutable global variable must use the mut keyword, and when using a mutable global variable, the unsafe keyword must be used.

Using Global Variables#

In Rust, using global variables requires the use of fully qualified paths. For example, for the global variable GLOBAL_VAR defined above, we can use its value anywhere in the program:

fn main() {
    println!("{}", GLOBAL_VAR);
}

In the code above, we accessed the value of the global variable GLOBAL_VAR using a fully qualified path and printed it to the console.

Safety of Global Variables#

In Rust, special attention must be paid to concurrency safety issues when using global variables. Since global variables can be used anywhere in the program, they may lead to data races and other problems. To address these issues, Rust provides some special mechanisms to ensure the safety of global variables.

One common method is to use synchronization mechanisms such as Mutex or RwLock.

Example 1#

For example, we can define the global variable as follows:

use std::sync::Mutex;

static GLOBAL_VAR: Mutex<i32> = Mutex::new(42);

In the code above, we use Mutex to synchronize the global variable. When using the global variable, we need to acquire the lock of the Mutex to ensure that only one thread can access the global variable at a time:

fn main() {
    let mut global_var = unsafe { GLOBAL_VAR.lock().unwrap() };
    *global_var = 43;
    println!("{}", *global_var);
}

In the code above, we used the lock() method to acquire the lock of the Mutex and modified the value of the global variable to 43, finally printing the value of the global variable. It is important to note that acquiring the lock of the Mutex may fail, so we need to handle possible errors using the unwrap() method.

Example 2#

use std::sync::Mutex;

static mut TABLE: Mutex<Table> = Mutex::new(Table::new());

type Table = Vec<Entry>;

#[derive(Debug)]
#[allow(dead_code)]
struct Entry {
    key: i32,
    value: i32,
}

fn main() {
    let mut table = unsafe { TABLE.lock().unwrap() };
    // let mut entry = Entry { key: 1, value: 10 };
    *table = vec![Entry { key: 1, value: 10 }];
    println!("table: {:?}", table);
}

The code above demonstrates how to define a mutable global variable in Rust.

First, we used the use keyword to import std::sync::Mutex, which is a synchronization mechanism in Rust. Next, we defined a mutable global variable named TABLE, of type Mutex<Table>, using the static mut keyword. In Rust, using Mutex to protect the concurrency safety of shared data is a common practice.

In the main() function, we acquired the lock of TABLE and modified its value to a Vec containing one Entry. It is important to note that when using mutable global variables, the unsafe keyword must be used.

Finally, we printed the modified value of TABLE.

The use of global variables requires special attention to concurrency safety issues. Since global variables can be used anywhere in the program, they may lead to data races and other problems. To address these issues, Rust provides some special mechanisms to ensure the safety of global variables, such as Mutex, RwLock, Atomic, and Channel. When using global variables, we need to choose the appropriate synchronization mechanism based on the actual situation to ensure the concurrency safety of the program.

Conclusion#

In this article, we introduced how to define and use global variables in Rust. Through global variables, we can share data within a program, improving code reusability and maintainability. At the same time, due to Rust's safety design, we need to pay special attention to the safety issues of global variables. We hope this article helps everyone in learning Rust.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.