Safe, single-threaded global state in Rust.
Debug assertions are present to ensure:
RefCell
)Single-threaded global state is a bit of a boogeyman in Rust:
static mut
is heavily discouraged due to its easy ability to cause UB through aliasing.First, add singlyton
as a dependency of your project in your Cargo.toml
file:
toml
[dependencies]
singlyton = "*"
Singleton
```rust use singlyton::Singleton;
static SINGLETON: Singleton<&'static str> = Singleton::new("Hello"); debugasserteq!(*SINGLETON.get(), "Hello");
SINGLETON.replace("Test"); debugasserteq!(*SINGLETON.get(), "Test");
SINGLETON.get_mut() = "Test 2"; debug_assert_eq!(SINGLETON.get(), "Test 2"); ```
SingletonUninit
```rust use singlyton::SingletonUninit;
static SINGLETON: SingletonUninit
SINGLETON.init("Hello".tostring()); debugasserteq!(SINGLETON.get().asstr(), "Hello");
SINGLETON.replace("Test".tostring()); debugasserteq!(SINGLETON.get().asstr(), "Test");
*SINGLETON.getmut() = "Test 2".tostring(); debugasserteq!(SINGLETON.get().as_str(), "Test 2"); ```