no-std globals

Painless global variables in Rust

13 releases (5 stable)

Uses new Rust 2021

1.0.4 Jul 16, 2022
1.0.2 Nov 13, 2020
1.0.1 Nov 12, 2019
0.1.3 Nov 3, 2019
0.0.4 Mar 20, 2019

#439 in Rust patterns

Download history 72/week @ 2022-06-05 19/week @ 2022-06-12 36/week @ 2022-06-19 18/week @ 2022-06-26 33/week @ 2022-07-03 57/week @ 2022-07-10 78/week @ 2022-07-17 58/week @ 2022-07-24 39/week @ 2022-07-31 49/week @ 2022-08-07 30/week @ 2022-08-14 56/week @ 2022-08-21 21/week @ 2022-08-28 59/week @ 2022-09-04 42/week @ 2022-09-11 43/week @ 2022-09-18

179 downloads per month
Used in 5 crates


70 lines

🌍 Globals

docs.rs docs

Painless globals in Rust. Works with any type that implements Default trait.

When I first started studying Rust, getting a simple global variable was oddly difficult. As I became more experienced, I got tired of these weird macros hanging around my code. This is a library for people who like the simplicity of global singleton in a single one liner and instantiation with standard Default trait. This library also uses no standard library by default so it's great for web assembly and embedded development where you want as little extra as possible. Enjoy.

Edit as per Rust 1.63 - This library is less necessary thanks to static mutexes now being supported more broadly, but this library is still useful for lazy globals.

globals = "1"
  • #![no_std] + alloc
  • leaves your code nice and clean


struct Foo {

impl Default for Foo {
  fn default() -> Self {
    Foo {v:42}

fn main() {
  let f = globals::get::<Foo>();

How this works

Rust is a language that values memory safety. When it comes to globals, this means making sure there's exclusive access to things that can be written to. The primary mechanism for protecting globals which could potentially have multiple threads interacting with it is the Mutex. globals has a HashMap of singletons of various types stored in a Mutex. When you call get() it looks up your singleton, if it doesn't exist, it calls the Default trait method default() implementation of type to create the singleton instance and stores it in the hashmap. When get() is called, this Mutex wrapped singleton is locked and a handle is given to safely interact with this mutex wrapped value called a MutexGaurd<T>. You can interact with the mutex guard as if it were your singleton type (this why it magically looks like you are just interacting with a global). Once your mutex gaurd is dropped, your mutex is unlocked for other threads to interact with your singleton.


This project is licensed under either of

at your option.


Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in globals by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.