我有几个JSON文件,它们在顶层只是包含不同类型数据的数组,所以如果有一个函数以通用的方式处理这一问题就好了.
这就是我到目前为止所拥有的(rust playground link):
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use serde::Deserialize;
fn get_json<'a, T: Deserialize<'a>>(path: &Path) -> Vec<T> {
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let sentences: Vec<T> = serde_json::from_reader(reader).unwrap();
sentences
}
我真的不明白它会带来什么错误,或者我如何才能让借款判断员相信一切都很好:
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/lib.rs:10:29
|
6 | fn get_json<'a, T: Deserialize<'a>>(path: &Path) -> Vec<T> {
| -- lifetime `'a` defined here
...
10 | let sentences: Vec<T> = serde_json::from_reader(reader).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ requires that `'a` must outlive `'static`
|
note: due to current limitations in the borrow checker, this implies a `'static` lifetime
--> /playground/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.107/src/de.rs:2591:8
|
2591 | T: de::DeserializeOwned,
| ^^^^^^^^^^^^^^^^^^^^
error: implementation of `Deserialize` is not general enough
--> src/lib.rs:10:29
|
10 | let sentences: Vec<T> = serde_json::from_reader(reader).unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ implementation of `Deserialize` is not general enough
|
= note: `Vec<T>` must implement `Deserialize<'0>`, for any lifetime `'0`...
= note: ...but it actually implements `Deserialize<'1>`, for some specific lifetime `'1`
error: could not compile `playground` (lib) due to 2 previous errors
我能做些什么来解决这个问题?