Which one is better ? global_state


fn change(global_state: &mut u32) {
    *global_state += 1;
}

fn main() {
    let mut global_state = 0u32;

    change(&mut global_state);

    println!("Final state: {}", 




global_state);
}
use std::sync::Mutex;

static ARRAY: Mutex<Vec<i32>> = Mutex::new(Vec::new());

fn do_a_call() {
    ARRAY.lock().unwrap().push(1);
}

fn main() {
    do_a_call();
    do_a_call();
    do_a_call();

    let array = ARRAY.lock().unwrap();
    println!("Called {} times: {:?}", array.len(), array);
    drop(array);

    *ARRAY.lock().unwrap() = vec![3, 4, 5];

    println!("New singleton object: {:?}", ARRAY.lock(). unwrap());
}

source: Singleton in Rust / Design Patterns

Which is better is dependent on the situation. Passing the state by argument is significantly more flexible and generally preferred (it will make testing easier, for one). But it can also get very verbose sometimes if you have a complicated call graph, which the static solution mitigates somewhat at the expense of making the program flow harder to understand and debug.

2 Likes

If you can replace a static mutex with a local variable, I'd always do it. But in my opinion you are comparing apples with oranges. The first snippet is not a drop-in replacement for the second one. Once you need more than one mutable reference (e.g. in a multi-threaded environment where more than one thread wants to write to ARRAY), the first snippet won't do, whereas the second one would (in most use-cases I'd still prefer to pass the mutex as argument around and not keep it as a static variable).

3 Likes

thank for this experience

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.