#lazy-evaluation #immutability #cell #init #cache #caching #lazy

yanked 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.

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

#67 in #lazy

CC0 license

7KB
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
    }
}

Dependencies

~0.6–0.9MB
~14K SLoC