lazy-static.rs icon indicating copy to clipboard operation
lazy-static.rs copied to clipboard

Binding-less static procedures?

Open mcandre opened this issue 7 years ago • 5 comments

Could we get an additional macro pattern for lazy_static! that allows for lambda procs to run, without binding the result to a variable?

mcandre avatar Oct 28 '18 20:10 mcandre

When would the lambda run? lazy_static is called lazy static because the lambda is evaluated on first access. If you want that behavior, you can just make a lazy static of ().

sfackler avatar Oct 28 '18 20:10 sfackler

Interesting empty unit idea! Could we get an example added to the test suite? I'm trying to use the empty unit for this, but my syntax must be wrong somehow.

mcandre avatar Oct 28 '18 20:10 mcandre

Creating a unit lazy static is the same thing as creating a lazy static of any other type - your initializer does some computation and then returns ().

You can also just use the standard library's Once type for this: https://doc.rust-lang.org/std/sync/struct.Once.html

sfackler avatar Oct 28 '18 20:10 sfackler

I'm not sure. Looks like Once expects to run from a function scope, not outside of a function like with lazy_static.

Eh, I'm working around this by no longer creating my main function by macro, but instead inserting my macro into main, where I can also insert my "static" procedure.

Will release a new version of mcandre/tinyrick soon using this to hack together a basic caching dependency task tree.

Thanks again for working hard on lazy_static!

mcandre avatar Oct 28 '18 20:10 mcandre

All code runs from a function scope.

These two code samples are basically equivalent:

static ONCE: Once = Once::new();

fn init_stuff() {
    ONCE.call_once(|| do_stuff());
}
lazy_static! {
    static ref ONCE: () = do_stuff();
}

fn init_stuff() {
    *ONCE
}

sfackler avatar Oct 29 '18 03:10 sfackler