#global #variables #macro #var #declaring

global_var

Simple macro for declaring a global variable

1 unstable release

0.1.0 Oct 4, 2023

#2072 in Rust patterns

21 downloads per month

MIT license

7KB

use global_var::*;

// type and initializer
new_global_var!(Vec<u32>, Vec::new());

fn main() {
    foo();
    foo();
    bar();
    bar();
}

fn foo() {
    unsafe {
        let v = get_mut_global_var();
        v.push(3); 
        println!("{v:?}");
    }
}

fn bar() {
    unsafe {
        let v = get_mut_global_var();
        v.push(4); 
        println!("{v:?}");
    }
}

// prints 
// [3]
// [3, 3]
// [3, 3, 4]
// [3, 3, 4, 4]
use global_var::*;

// 2 different global variables
new_global_var!(GLOBAL_VAR1, FLAG1, init_global_var1, get_mut_global_var1, Vec<u32>, Vec::new());
new_global_var!(GLOBAL_VAR2, FLAG2, init_global_var2, get_mut_global_var2, Vec<u64>, Vec::new());

fn main() {
    foo();
    foo();
    bar();
    bar();
}

fn foo() {
    unsafe {
        let v = get_mut_global_var1();
        v.push(3); 
        println!("{v:?}");
    }
}

fn bar() {
    unsafe {
        let v = get_mut_global_var2();
        v.push(4); 
        println!("{v:?}");
    }
}

// prints
// [3]
// [3, 3]
// [4]
// [4, 4]

new_global_var!(HashMap<u32, u32>, HashMap::new()) creates 2 functions: init_global_var and get_mut_global_var. The first function init_global_var initializes a global version of HashMap<u32, u32>. It's safe to initialize multiple times. The second function get_mut_global_var returns &mut HashMap<_, _>. If it's not initialized yet, it calls init_global_var.

Even though it's a very convenient way to declare a global variable. There's a drawback: you can call this macro only once. If you call it multiple times, it would create global variables with the same name, which would cause a compile error. In order to use multiple global variables, you should use the verbose version of this macro. It looks like this: new_global_var!(GLOBAL_VAR_NAME, IS_INIT, init_global_var, get_mut_global_var, HashMap<u32, u32>, HashMap::new()). The first and the second identifiers are the names of the global variables (and the flag for initialization). You're not gonna use that names again, so feel free to name them. But be sure that the names are unique. The third and the forth ones are the functions that you're gonna use.

Since it's a static mut, different threads can access to a global variable. It's your job to use proper lock mechanisms.

No runtime deps