Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ravieze opened this issue Apr 13, 2023 · 1 comment

Comments

@ravieze
Copy link

ravieze commented Apr 13, 2023

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
Copy link
Author

ravieze commented Apr 19, 2023

Hi Team,

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant