从文件反序列化的通用函数中,如何处理缓冲区的生存期?

时间:2018-12-12 16:10:37

标签: generics rust traits lifetime

下面的最小示例就可以从磁盘读取一个结构:

extern crate bincode;
#[macro_use]
extern crate serde_derive;

use std::fs::File;
use std::io::Read;

use bincode::deserialize;

#[derive(Deserialize)]
struct Thing {
    something: u64,
}

fn load_thing_from_file(file_path: &str) -> Thing {
    // unwrap instead of actual error handling for brevity of this example.
    let mut file = File::open(file_path).unwrap();
    let mut buffer: Vec<u8> = Vec::new();
    file.read_to_end(&mut buffer).unwrap();
    let result: Thing = deserialize(&buffer[..]).unwrap();
    return result;
}

fn main() {
    let t = load_thing_from_file("thing.bin");
    println!("{}", t.something);
}

但是,当我尝试使加载函数通用时,就像这样:

extern crate bincode;
#[macro_use]
extern crate serde_derive;

use std::fs::File;
use std::io::Read;

use bincode::deserialize;

#[derive(Deserialize)]
struct Thing {
    something: u64
}

fn load_from_file<'de, T: serde::Deserialize<'de>>(file_path: &str) -> T {
    // unwrap instead of actual error handling for brevity of this example.
    let mut file = File::open(file_path).unwrap();
    let mut buffer: Vec<u8> = Vec::new();
    file.read_to_end(&mut buffer).unwrap();
    let result: T = deserialize(&buffer[..]).unwrap();
    return result;
}

fn main() {
    let t = load_from_file::<Thing>("thing.bin");
    println!("{}", t.something);
}

我得到:

error[E0597]: `buffer` does not live long enough
  --> src/main.rs:20:34
   |
20 |     let result: T = deserialize(&buffer[..]).unwrap();
   |                                  ^^^^^^ borrowed value does not live long enough
21 |     return result;
22 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'de as defined on the function body at 15:19...
  --> src/main.rs:15:19
   |
15 | fn load_from_file<'de, T: serde::Deserialize<'de>>(file_path: &str) -> T {
   |                   ^^^

如何解决此问题,以便编译器了解一切正常?

0 个答案:

没有答案