init

Macro init 

Source
macro_rules! init {
    () => { ... };
    (mod $($path:ident)::+) => { ... };
    (mod $($path:ident)::+, $($tail:tt)*) => { ... };
    ($path:path) => { ... };
    ($path:path, $($tail:tt)*) => { ... };
}
Expand description

Manually initializes the provided magic statics in the specified order.

Does nothing to a magic static if it has already been initialized.

§Safety

The following behaviour is considered undefined:

  • Initializing magic statics from multiple threads concurrently.
  • Spawning new threads and accessing magic statics during initialization from them.
  • Interior mutability of magic statics where the mutability is not synchronized across multiple threads (e.g. with a Mutex or RwLock.) This is not a problem for single-threaded applications.

§Example

mod foo {
    magic_static! {
        pub(super) static ref BAR: std::sync::Mutex<()> = std::sync::Mutex::new(());
        pub(super) static ref MAGIC: usize = {
            println!("Magic!");
            42
        };
    }
}

// You can also modularize your magic statics like so:
mod baz {
    magic_static! {
        pub(super) static ref MAGIC: usize = {
            println!("Magic!");
            42
        };

        pub(super) static ref BAR: std::sync::Mutex<()> = std::sync::Mutex::new(());
    }

    #[magic_static::main(
        MAGIC,
        BAR
    )]
    // Must be called `magic_static`
    pub fn magic_static() {}
}

fn main() {
    magic_static::init! {
        foo::BAR,
        foo::MAGIC,
        mod baz // This will initialize all magic statics in `baz`
    }
}