rust-lang-nursery / lazy-static.rs

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

Accessing lazy_static from another struct in a new file throws `Option::unwrap()` on a `None` #210

Open ravieze opened 1 year ago

ravieze commented 1 year ago

Issue:

  1. I created a lazy-static ref, initialized it, and printed it. It prints well --called in main thread
  2. The same lazy-static ref when called from another struct from another .rc file return None --this struct is called from main thread

is this expected behavior? Basically i want to have a set of singleton structs --as silo services, initialize them and keep them, so that i can call any service as per the usecase.

rockdb.rc

lazy_static! {
    pub static ref KV_STORE: OnceCell<KVStoreSt> = OnceCell::new();
}

#[derive( Debug)]
pub struct KVStoreSt {
    db:  DB,
}

impl KVStoreSt {
    pub async fn init() {
        if KV_STORE.get().is_none() {
            info!("creating rockdb");
            let path = PathBuf::from("/tmp/kvstore");
            std::fs::create_dir_all(path).expect("couldnt create the folder for the kv store");
            let rockdb =  DB::open_default("/tmp/kvstore");
            .expect(&format!("couldnt create rockdb; path:{}", file_path));
            let kv_store = KVStoreSt {
                db:  rockdb, 
            };
            KV_STORE.set(kv_store).unwrap();
            info!(">>>kvstore::{:?}", KV_STORE.get().unwrap());
      }
   }

pub async fn inst(file_path: &str) -> &KVStoreSt {
       return KV_STORE.get().unwrap();
}

}

When init() is called the above info! is printed fine.

Below is the main thread.

#[tokio::main]
async fn main() {
    KVStoreSt::init().await;
    info!("<><><> {:?}",kvstore().await);
   ZZZ::init2().await;
}

The last line above throws error

thread 'main' panicked at 'called `Option::unwrap()` on a `None` 

sch2.rc


pub struct ZZZ;

impl ZZZ {
    pub async fn init2() {
        println!("kvstore ... {:?}", KVStoreSt::inst("file_path").await);
    }
}
ravieze commented 1 year ago

Hi Team,

It has been a week. Any update on this, please? Is my approach wrong? am i overlooking something important?