2017-05-27 30 views
0

我有這樣的代碼:不能在lazy_static HashMap中的引用返回一個元素,因爲它不活足夠長的時間

#[macro_use] 
extern crate lazy_static; 

use std::collections::HashMap; 
use std::cell::RefCell; 
use std::sync::{RwLock, RwLockReadGuard, LockResult}; 

lazy_static! { 
    static ref SUBS: RwLock<HashMap<String, String>> = RwLock::new(HashMap::new()); 
} 

pub fn get_sub(key: &str) -> Option<&String> { 
    let subs: LockResult<RwLockReadGuard<HashMap<String, String>>> = SUBS.read(); 
    let x: RwLockReadGuard<HashMap<String, String>> = subs.unwrap(); 
    x.get(key) 
} 

而且這不會編譯:

error: `x` does not live long enough 
    --> src/main.rs:15:5 
    | 
15 |  x.get(key) 
    | ^does not live long enough 
16 | } 
    | - borrowed value only lives until here 
    | 
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 12:45... 
    --> src/main.rs:12:46 
    | 
12 | pub fn get_sub(key: &str) -> Option<&String> { 
    | ______________________________________________^ starting here... 
13 | |  let subs: LockResult<RwLockReadGuard<HashMap<String, String>>> = SUBS.read(); 
14 | |  let x: RwLockReadGuard<HashMap<String, String>> = subs.unwrap(); 
15 | |  x.get(key) 
16 | | } 
    | |_^ ...ending here 

我完全難倒。我不明白爲什麼這不編譯。

回答

1

您正在返回對哈希表中對象的引用,哈希表中的對象可以隨時被其他人修改/刪除。

最簡單的方法是克隆它:

pub fn get_sub(key: &str) -> Option<String> { 
    //        ^~~~~~ change the signature 
    let subs: LockResult<RwLockReadGuard<HashMap<String, String>>> = SUBS.read(); 
    let x: RwLockReadGuard<HashMap<String, String>> = subs.unwrap(); 
    x.get(key).cloned() 
    //   ^~~~~~ Option::cloned() 
} 

在你想要一個完全不變(immutable)的查找表的情況下,簽出phf箱子。

相關問題