Member-only story

A Brief Discussion on Lazy Loading in Rust

Beck Moulton
3 min readMay 7, 2024

--

Let’s learn about lazy loading in Rust today.

once_cell

The once_celllibrary provides two new cell-like types, un sync :: OnceCelland sync :: OnceCell. OnceCellmay store any non- Copytype, can be assigned at most once, and provides direct access to the stored content.

The core API is roughly as follows:

impl<T> OnceCell<T> {
const fn new() -> OnceCell<T> { ... }
fn set(&self, value: T) -> Result<(), T> { ... }
fn get(&self) -> Option<&T> { ... }
}

Note that like RefCelland Mutex, the setmethod only requires a shared reference. Due to the single assignment limitation, getcan return & Tinstead of Ref < T >or MutexGuard < T >.

Additionally, once_cellhave a Lazy < T >type based on OnceCellthat provides the same API as the lazy_static!macro, but without using any macros:

use std::{sync::Mutex, collections::HashMap};
use once_cell::sync::Lazy;static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = Lazy::new(|| {
let mut m = HashMap::new();
m.insert(13, "Spica".to_string());
m.insert(74, "Hoyten".to_string());
Mutex::new(m)
});fn main() {
println!("{:?}", GLOBAL_DATA.lock().unwrap());
}

Note that variables holding Lazyare declared static, not const. This is important: using constinstead can compile, but it doesn't work properly.

why not lazy_static!

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet