SergioBenitez / state

A Rust library for safe and effortless global and thread-local state management.
Other
213 stars 14 forks source link

Thunk Example #14

Closed wyhinton closed 3 years ago

wyhinton commented 3 years ago

In the docs you mention that we can use State to create thunks. Is there any example of this somewhere?

SergioBenitez commented 3 years ago

There isn't. Here's what lots of my code looks like that uses Storage to create a thunk:

struct Foo {
    data_for_expensive_computation: Data,
    expensive: Storage<Expensive>,
}

impl Foo {
    fn dont_need_expensive() -> T;

    fn do_need_expensive(&self) -> &Expensive {
        self.expensive.get_or_set(|| do_expensive(&self.data_for_expensive_computation))
    }
}

Here, the "thunk" is really Foo instead of Storage as it's what carries the state required to actually force the thunk.

wyhinton commented 3 years ago

Looks great, thanks!