Const LazyCell calls initializer mutliple times
⚓ Rust 📅 2026-03-28 👤 surdeus 👁️ 2Consider the following code:
#[test]
fn foo() {
const FOO: LazyCell<()> = LazyCell::new(|| eprintln!("init_FOO"));
let bar: LazyCell<()> = LazyCell::new(|| eprintln!("init_bar"));
LazyCell::force(&FOO);
LazyCell::force(&FOO);
LazyCell::force(&bar);
LazyCell::force(&bar);
}
I would expect running this test to print:
init_FOO
init_bar
However, I instead see:
init_FOO
init_FOO
init_bar
It appears that by moving the LazyCell to a global const, it stops working as expected, and instead recalls the initializer on every access.
My motivation for using LazyCell is to have the cell be a global to avoid repeating an expensive initailization call, and I don't think there is an easy way to accomplish that without making it const.
2 posts - 2 participants
🏷️ Rust_feed