Is there a way I can define a static module?

Is there a package or macro that can work like this:

#[gen_var_set]
mod my_var_set {
    let a = 1;
    let b = 2;
    let c = 3;
}

#[gen_var_set]
mod my_var_set2 {
    let a = Box::new(1);
    let b = MyStruct;
}

Then I can use the mod defined above like this:

my_var_set::a;

my_var_set2::b;

You could use constants and/or lazy_static for this:

#![allow(non_upper_case_globals)]

mod my_var_set {
    pub const a: u8 = 1;
    pub const b: u8 = 2;
    pub const c: u8 = 3;
}

mod my_var_set2 {
    use lazy_static::lazy_static;
    
    // Box::new is not const, so we need to use lazy_static
    lazy_static! {
        pub static ref a: Box<i32> = Box::new(1); 
    }
    
    pub const b: MyStruct = MyStruct;
    
    #[derive(PartialEq, Debug)]
    pub struct MyStruct;
}

fn main() {
    assert_eq!(my_var_set::a, 1);
    assert_eq!(my_var_set::b, 2);
    assert_eq!(my_var_set::c, 3);
    
    assert_eq!(**my_var_set2::a, 1);
    assert_eq!(my_var_set2::b, my_var_set2::MyStruct);
}

Playground.

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.