liveBook · Manning

Lazy_static

As explained in Code Like a Pro in Rust

lazy_static is a Rust crate and macro that provides lazily initialized static values, including values initialized at runtime.

lazy_static provides lazily initialized static values when initialization must occur at runtime rather than in a constant expression. It is especially useful for global test fixtures and shared state under parallel test execution. section 6.5

Use it to:

  • Declare a static atomic counter with lazy_static! when direct Arc initialization in a static is rejected. section 6.5
  • Combine lazy initialization with AtomicI32 for counters or Mutex for serialized access to shared mutable test state. section 6.5

Lazy atomic counter

lazy_static! { static ref COUNT: AtomicI32 = AtomicI32::new(0); } #[test] fn test_count() { COUNT.fetch_add(1, Ordering::SeqCst); } section 6.5

#[allow(missing_copy_implementations)]
#[allow(non_camel_case_types)]
#[allow(dead_code)]
struct COUNT {
    __private_field: (),
}
#[doc(hidden)]
static COUNT: COUNT = COUNT {
    __private_field: (),
};
impl ::lazy_static::__Deref for COUNT {                   #1
    type Target = Arc<AtomicI32>;
    fn deref(&self) -> &Arc<AtomicI32> {
        #[inline(always)]
        fn __static_ref_initialize() -> Arc<AtomicI32> {
            Arc::new(AtomicI32::new(0))                   #2
        }
        #[inline(always)]
        fn __stability() -> &’static Arc<AtomicI32> {
            static LAZY: ::lazy_static::lazy::Lazy<Arc<AtomicI32>> =
                ::lazy_static::lazy::Lazy::INIT;          #3
            LAZY.get(__static_ref_initialize)             #3
        }
        __stability()
    }
}
impl ::lazy_static::LazyStatic for COUNT {
    fn initialize(lazy: &Self) {
        let _ = &**lazy;
    }
}

Inspect the macro expansion to see the generated dereference layer and one-time lazy initialization machinery. section 6.5

How Code Like a Pro in Rust covers it

How deep it goes
Explains macro usage, failed static initialization, atomic and mutex patterns, and generated lazy machinery.
Examples
Demonstrates atomic counters, Arc-wrapped counters, and mutex-protected test output.
What it assumes
Assumes Rust familiarity and introduces the static initialization and parallel-test problems through concrete failures.
What you can do after
Apply it via the lazy_static crate to define runtime-initialized static references for concurrent tests.
How it connects
Connects static variables with unit testing, atomic integers, Arc, Mutex, and the libtest harness.

Also explained in

Compare how 2 books explain lazy_static →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.