从全局结构访问数据时出现错误 "borrowed value does not live long enough"

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

根据thread,我需要创建一个全局非可变单例来存储一些静态数据。

#[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 as *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());
    }
    // This doesn't work as 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);

}

它是单线程的,所以我没有使用 Arc/Mutex。

如何让 RefData::singleton() 持续足够长的时间以 return 引用 btreemap

中的值

It's single threaded so I'm not using Arc/Mutex.

实际上,这是第一期。

ArcMutex 提供 更多 不仅仅是线程安全,它们还提供 浅拷贝,这样所有 SingletonReader 共享下面的相同存储,因此存储的生命周期与 SingletonReader.

的生命周期无关

因此,您应该 return &'static 引用 RefData

fn singleton() -> &'static RefData {
    static mut g_RefData : *const RefData = 0 as *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
   }
}

现在,这个实现将起作用:

fn vol_handle(asset : &str) -> Option<&String> {
    RefData::singleton().atm_vol.get(asset)
}

然而,它略有偏差:生命周期推断使得它被解释为:

fn vol_handle<'a>(asset : &'a str) -> Option<&'a String> {
    RefData::singleton().atm_vol.get(asset)
}

这可能不是您想要的,因为 String 的生命周期实际上是 'static,因此您应该瞄准:

fn vol_handle(asset : &str) -> Option<&'static String> {
    RefData::singleton().atm_vol.get(asset)
}