无法返回对lazy_static HashMap中元素的引用,因为它的活动时间不够长

时间:2017-05-27 23:30:03

标签: rust

我有这样的代码:

#[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 个答案:

答案 0 :(得分: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()
}

如果您想要一个完全恒定(不可变)的查找表,请查看phf包。