rust - 无法返回对lazy_static HashMap中元素的引用,因为它的生存时间不够长

标签 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

我完全被难住了。我不明白为什么这不能编译。

最佳答案

您将返回对哈希表内对象的引用,其他人可以随时更改/删除该对象。

最简单的方法是克隆它:

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 crate 。

关于rust - 无法返回对lazy_static HashMap中元素的引用,因为它的生存时间不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222478/

相关文章:

reference - 如何创建一个工厂函数,其中您正在创建的数据需要引用?

rust - 如何在不出错的情况下实现Ord特质 “use of unstable library feature ' clip'”?

rust - 如何在 Rust 中将两个 i16 相加或相乘形成一个 i32 而不会溢出?

function - 如何在Rust中命名关联函数的类型?

rust - 将大小为 N 的向量转换为超过 32 的固定大小数组长度 N

rust - 将任何 Diesel 表作为参数传递

rust - "cycle detected when computing the supertrait"怎么解决?

rust - 是否有以十六进制表示法声明字 rune 字的语法?

c - 将 Rust staticlib 与 C 链接后出现段错误

linux - 如何找到我的 Rust 项目的哪一部分使用 GLIBC 2.18