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

