rust - Acessing data from a global struct, gives error "borrowed value does not live long enough" -


as per thread i've had need create global non-mutable singleton store static data.

#[derive(clone)] struct refdata {     atm_vol : btreemap<string,string>,     delta_vol : btreemap<string,string> }  impl refdata {     fn singleton() -> refdata {         static mut g_refdata : *const refdata = 0 *const refdata;         static g_once : once = once_init;         unsafe {             g_once.call_once(|| {                 let mut ref_data = refdata { atm_vol : (btreemap::new()),                                              delta_vol : (btreemap::new()) };                 ref_data.init();                 g_refdata = mem::transmute(box::new(ref_data));                 });              (*g_refdata).clone()        }     }      fn init(&mut self) {         self.atm_vol.insert("xcu".to_string(),"xcu_usd_vol_dt".to_string());         self.delta_vol.insert("xcu".to_string(),"xcu_usd_vol_skew_m".to_string());     }     // doesn't work singleton doesn't last long enough     fn vol_handle(asset : &str) -> option<&string> {         refdata::singleton().atm_vol.get(asset)     } }   #[test] fn test_refdata() {     let t = refdata::vol_handle("xcu");     println!("{:?}",t);  } 

it's single threaded i'm not using arc/mutex.

how can refdata::singleton() last long enough return reference value thats in btreemap

it's single threaded i'm not using arc/mutex.

and is, actually, first issue.

arc , mutex provide more thread-safety, provide shallow copies, singletonreader share same storage underneath, , therefore lifetime of storage not linked of singletonreader.

thus, should rather return &'static reference refdata.

fn singleton() -> &'static refdata {     static mut g_refdata : *const refdata = 0 *const refdata;     static g_once : once = once_init;     unsafe {         g_once.call_once(|| {             let mut ref_data = refdata { atm_vol : (btreemap::new()),                                          delta_vol : (btreemap::new()) };             ref_data.init();             g_refdata = mem::transmute(box::new(ref_data));             });          &*g_refdata    } } 

and now, implementation work:

fn vol_handle(asset : &str) -> option<&string> {     refdata::singleton().atm_vol.get(asset) } 

however, skewed: lifetime inference makes interpreted as:

fn vol_handle<'a>(asset : &'a str) -> option<&'a string> {     refdata::singleton().atm_vol.get(asset) } 

which perhaps not wish for, lifetime of string 'static here, , therefore should rather aim for:

fn vol_handle(asset : &str) -> option<&'static string> {     refdata::singleton().atm_vol.get(asset) } 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -