Dynamic statics using the lazy_static! macro

As we have seen, global values can only be declared for types that are non-dynamic in their initialization and have a known size on the stack at compile time. For example, you can't create a HashMap as a static value because it requires a heap allocation. Fortunately, we can have HashMap and other dynamic collection types such as Vec as global statics too, using a third-party crate called lazy_static. This crate exposes the lazy_static! macro, which can be used to initialize any dynamic type that's accessible globally from anywhere in the program. Here's a snippet of how to initialize a Vec that can be mutated from multiple threads:

// lazy_static_demo

use std::sync::Mutex;

lazy_static! {
static ref ITEMS: Mutex<Vec<u64>> = {
let mut v = vec![];
v.push(9);
v.push(2);
v.push(1);
Mutex::new(v)
}
}

Items declared within the lazy_static! macro are required to implement the Sync trait. This means if we want a mutable static, we have to use a multithreaded type such as Mutex or RwLock instead of  RefCell. We'll explain these types when we get to Chapter 8, Concurrency. We'll be using this macro frequently in future chapters. Head over to the crate repository to learn more about using lazy_static.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset