gpt4 book ai didi

rust - 修复使用 lazy_static 时的 serde 生命周期问题

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

我想将一些 json 读入静态 HashMap ,并且正在使用 lazy_staticserde ,但我不知道如何(如果有的话)解决这个 serde终身问题:

#[macro_use]
extern crate lazy_static;
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;

lazy_static! {
static ref KEYWORDS: HashMap<&'static str, i32> = {
let file = File::open("words.json").unwrap();
let reader = BufReader::new(file);
serde_json::from_reader(reader).unwrap()
};
}

playground link

error: implementation of serde::de::Deserialize is not general enough
note: HashMap<&str, i32> must implement serde::de::Deserialize<'0>, for any lifetime '0
note: but HashMap<&str, i32> actually implements serde::de::Deserialize<'1>, for some specific lifetime '1

words.json是一个简单的 json 映射:{"aaargh": 1} .

我对另一个人开放,非lazy_static如果需要的话。

最佳答案

使用 serde_json::from_str 时从 &str 反序列化⟶ HashMap<&str, i32> ,输入的 JSON 字符串需要比输出中的字符串切片更长寿。这就是'a的作用签名中的生命周期:https://docs.rs/serde_json/1.0.40/serde_json/fn.from_str.html

这意味着如果输出需要包含带有 'static 的字符串切片生命周期,输入的 JSON 数据还必须有 'static生命周期。我们知道如何做到这一点 -- lazy_static!

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
static ref KEYWORDS: HashMap<&'static str, i32> = {
lazy_static! {
static ref WORDS_JSON: String = {
std::fs::read_to_string("words.json").unwrap()
};
}
serde_json::from_str(&WORDS_JSON).unwrap()
};
}

关于rust - 修复使用 lazy_static 时的 serde 生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018880/

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