#lazy #cell #cache #init #immutable

lazyonce

Store “immutable” cell that computes its value once, when it’s first accessed. Allows lazy initialization as an implementation detail, without need to expose any mutable methods.

3 releases (1 stable)

1.0.0 Jul 20, 2019
0.3.0 Dec 9, 2018
0.2.0 Jun 14, 2018

#1096 in Rust patterns

CC0 license

6KB
98 lines

Lazy one-time initialization

It's like std::sync::Once, but holds the result. It's like lazy_static!, but works for non-static values.

It's a tiny helper library used to initialize some computed properties in crates.rs projects without having to make the method calls mutable.


lib.rs:

Wrapper type for lazy initialization

Store "immutable" cell that computes its value once, when it's first accessed. Allows lazy initialization as an implementation detail, without need to expose any mutable methods.

It's like lazy_static, but not static. It's like std::sync::Once, but holds a value.

It's thread-safe (Send and Sync).

use lazyonce::LazyOnce;
struct Oracle {
    answer: LazyOnce<u32>,
}

impl Oracle {
    pub fn get_answer(&self) -> &u32 {
        self.answer.get(|| think()) // think() is called only once
    }
}
# fn think() -> u32 {42}

Dependencies

~605KB
~11K SLoC