rust-lang-nursery / lazy-static.rs

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

Support tuple syntax #184

Closed vedantroy closed 3 years ago

vedantroy commented 3 years ago

Would it be possible for the macro to support the following?

lazy_static! {
    static ref (a, b): (usize, usize) = { (1, 2) };
}

I have the following use-case. Right now, I'm opening 3 different "trees/keyspaces" in Sled. I want to prevent people from using the default keyspace, which is accessible through __DB__. Essentially, I want __DB__ to be hidden/private. A tuple could solve this.

Current code

lazy_static! {
    static ref __DB__: Db = sled::open(DB_PATH).unwrap();
    static ref ALL: sled::Tree = __DB__.open_tree("foo").unwrap();
    static ref TO_PROCESS: sled::Tree = __DB__.open_tree("bar").unwrap();
    static ref FOR_REFILL: sled::Tree = __DB__.open_tree("baz").unwrap();
}

Proposed code:

lazy_static! {
   static ref (ALL, TO_PROCESS, FOR_REFILL): (sled::Tree, sled::Tree, sled::Tree) = {
      let db = sled::open(DB_PATH).unwrap();
     (db.open_tree("foo").unwrap(), db.open_tree("bar").unwrap(), ...)
   }
}

Update: Guessing this wouldn't work anyway because db would be dropped by the end of the scope, not sure.

Kimundi commented 3 years ago

The macro was never intended to support more than what the static keyword supports on its own.

Eg this is invalid as well:

static (FOO, BAR): (u8, u8) = (1, 2);

What you are describing should be solvable just via privacy though, by ensuring __DB__ is private to the module that defines it.

Feel free to re-open otherwise. :)