Câu hỏi phỏng vấn Rust
Câu hỏi

Is it possible to use g...

Câu trả lời

Yes, it is possible to use global variables in Rust, but it comes with certain caveats and best practices to ensure safety and proper usage.

Declaring Global Variables

In Rust, global variables are declared using the static keyword. A static variable has a 'static lifetime, meaning it exists for the entire duration of the program. Here is a basic example of declaring a global variable:

static GLOBAL: i32 = 10;

Mutable Global Variables

If you need a mutable global variable, you can declare it with static mut. However, accessing and modifying static mut variables is unsafe and must be done within an unsafe block to prevent data races and ensure thread safety:

static mut COUNTER: i32 = 0;

fn increment() {
    unsafe {
        COUNTER += 1;
    }
}

fn main() {
    increment();
    increment();
    unsafe {
        println!("Counter value: {}", COUNTER);
    }
}

Alternatives to Global Variables

Rust encourages avoiding global mutable state due to potential safety issues. Instead, you can use several alternatives:

  1. Thread-safe Wrappers: Use thread-safe wrappers like Mutex, RwLock, or atomic types to manage mutable global state safely.

    use std::sync::Mutex;
    
    static GLOBAL_MUTEX: Mutex<i32> = Mutex::new(0);
    
    fn increment() {
        let mut num = GLOBAL_MUTEX.lock().unwrap();
        *num += 1;
    }
  2. Lazy Initialization: Use crates like lazy_static or once_cell for lazy initialization of global variables.

    use lazy_static::lazy_static;
    use std::sync::Mutex;
    
    lazy_static! {
        static ref GLOBAL: Mutex<i32> = Mutex::new(0);
    }
    
    fn increment() {
        let mut num = GLOBAL.lock().unwrap();
        *num += 1;
    }
  3. Passing State: Pass state explicitly through function arguments or use data structures to encapsulate state.

Const vs Static

  • const: Represents compile-time constants. These are inlined wherever they are used and do not have a fixed memory address.

    const MAX_SIZE: i32 = 100;
  • static: Represents a single memory location that is shared across th...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Explain what is Send and Sync in Rust and when do you need them?

junior

What is Rust?

middle

Why are Rust executables so huge? How would you optimise it?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào