rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

Binding-less static procedures? #129

Open mcandre opened 5 years ago

mcandre commented 5 years ago

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

sfackler commented 5 years ago

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 ().

mcandre commented 5 years ago

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.

sfackler commented 5 years ago

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

mcandre commented 5 years ago

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!

sfackler commented 5 years ago

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
}