#init #static #lazy-evaluation #global #macro

no-std sly_static

Seamless Rust Static Initialization: Effortless and Efficient

7 stable releases

1.0.6 Sep 16, 2024
1.0.5 Apr 5, 2024
1.0.3 Feb 23, 2024

#1298 in Rust patterns

Download history 6/week @ 2024-08-27 3/week @ 2024-09-03 60/week @ 2024-09-10 144/week @ 2024-09-17 19/week @ 2024-09-24 22/week @ 2024-10-01

298 downloads per month

MIT license

5KB

sly_static

Seamless Rust Static Initialization: Effortless and Efficient

What is this?

This crate allows you to initialize static variables easily (automaticlly) inside main function.

How does it work?

Uses the linkme crate to collect all the static variables and initialize them inside the main function. It makes use of some code from ctor to initialize the statics.

Warning

It uses unsafe code to initialize the statics, but it's safe to use unless you do some weird magic with it.

I say it's safe because all the statics are initialized inside the main function, so there's no way to access them before they are initialized.

Example

use sly_static::sly_static;
use sly_static::sly_main;

#[sly_static]
static MY_STATIC: String = String::from("Hello, World!");

#[sly_main]
fn main() {
    println!("{}", *MY_STATIC);
}

License: MIT


lib.rs:

Seamless Rust Static Initialization: Effortless and Efficient

What is this?

This crate allows you to initialize static variables easily (automaticlly) inside main function.

How does it work?

Uses the linkme crate to collect all the static variables and initialize them inside the main function.

It makes use of some code from ctor to initialize the statics.

Warning

It uses unsafe code to initialize the statics, but it's safe to use unless you do some weird magic with it.

I say it's safe because all the statics are initialized inside the main function, so there's no way to access them before they are initialized.

Example

use sly_static::sly_static;
use sly_static::sly_main;

#[sly_static]
static MY_STATIC: String = String::from("Hello, World!");

#[sly_main]
fn main() {
    println!("{}", *MY_STATIC);
}

Dependencies

~265–720KB
~17K SLoC