- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将一些 json 读入静态 HashMap
,并且正在使用 lazy_static
和 serde
,但我不知道如何(如果有的话)解决这个 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()
};
}
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/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!