本文介绍了创建返回实现 serde::Deserialize 的值的函数时出现生命周期错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 serde 和 serde_json 1.0 从 base64 字符串解码数据:

I'm using serde and serde_json 1.0 to decode data from a base64 string:

fn from_base64_str<T: Deserialize>(string: &str) -> T {
    let slice = decode_config(string, URL_SAFE).unwrap();
    serde_json::from_slice(&slice).unwrap()
}

当我编译时,我得到了这个:

When I compile, I got this:

error[E0106]: missing lifetime specifier
 --> src/main.rs:6:23
  |
6 | fn from_base64_str<T: Deserialize>(string: &str) -> T {
  |                       ^^^^^^^^^^^ expected lifetime parameter

查看serde doc,Deserialize定义为:

Checking the serde doc, Deserialize is defined as:

pub trait Deserialize<'de>: Sized {

所以我添加了生命周期:

So I added the lifetime:

fn from_base64_str<'de, T: Deserialize<'de>>(string: &str) -> T {
    let slice = decode_config(string, URL_SAFE).unwrap();
    serde_json::from_slice(&slice).unwrap()
}

然后编译器告诉我:

error: `slice` does not live long enough
  --> src/main.rs:11:29
   |
11 |     serde_json::from_slice(&slice).unwrap()
   |                             ^^^^^ does not live long enough
12 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'de as defined on the body at 9:64...
  --> src/main.rs:9:65
   |
9  |   fn from_base64_str<'de, T: Deserialize<'de>>(string: &str) -> T {
   |  _________________________________________________________________^ starting here...
10 | |     let slice = decode_config(string, URL_SAFE).unwrap();
11 | |     serde_json::from_slice(&slice).unwrap()
12 | | }
   | |_^ ...ending here

我只知道 Rust 中生命周期的基础知识,所以我对 trait Deserialize 中的 'de 感到非常困惑.

I only know the very basics of lifetimes in Rust, so I'm very confused by the 'de in trait Deserialize.

如何修复此类函数中的生命周期错误?我每晚使用 Rust 1.18.0 (452bf0852 2017-04-19)

How can I fix the lifetime error in such function? I'm using Rust 1.18.0-nightly (452bf0852 2017-04-19)

推荐答案

我从 Serde 问题 891:我应该使用 DeserializeOwned 而不是 Deserialize.

I found an answer from Serde issue 891: I should use DeserializeOwned instead of Deserialize.

这篇关于创建返回实现 serde::Deserialize 的值的函数时出现生命周期错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 04:48