gpt4 book ai didi

rust - 无法返回对 lazy_static HashMap 中元素的引用,因为它的生命周期不够长

转载 作者:行者123 更新时间:2023-11-29 08:18:52 25 4
gpt4 key购买 nike

<分区>

我有这样的代码:

#[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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com