【发布时间】:2021-05-16 19:32:25
【问题描述】:
我正在为一个项目编写一个反序列化器(Vec<u8>(Raw JSON)到任何类型的 T)并尝试使用 serde。这是我解码数据的特征:
pub trait Decode: Sized {
fn try_decode(input: Vec<u8>) -> Result<Self, InternalError>;
}
因为我打算在我的结构上使用#[derive(Deserialize)],所以我正在为任何实现具有任意生命周期的 Deserialize 特征的类型编写一个 impl:
impl<'a, T: Deserialize<'a>> Decode for T {
fn try_decode(input: Vec<u8>) -> Result<Self, InternalError> {
if let Ok(t) = serde_json::from_slice(&input) {
Ok(t)
} else {
Err(Internal::decode("Could not decode"))
}
}
}
但我遇到了终身错误:
error[E0597]: `input` does not live long enough
--> src/decode.rs:16:47
|
14 | impl<'a, T: Deserialize<'a>> Decode for T {
| -- lifetime `'a` defined here
15 | fn try_decode(input: Vec<u8>) -> Result<Self, InternalError> {
16 | if let Ok(t) = serde_json::from_slice(&input) {
| -----------------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `input` is borrowed for `'a`
...
21 | }
| - `input` dropped here while still borrowed
我明白编译器为什么生我的气了。在检查 from_slice 的实现后,我发现它有一个关联的生命周期。我确信输入是一个拥有的值,但 from_slice 需要一个引用,所以在这里我返回一个值的引用,该值在函数结束时被删除,这显然是不正确的。我的问题是,有没有办法确保在 生命周期内借用该值(即此函数的调用者提供的生命周期)。我无法更新特征,因为它会导致灾难。
【问题讨论】:
-
如果你想要一个不从切片中借用的值,你可以使用
DeserializeOwned作为特征绑定,它没有关联的生命周期(因此只存储拥有的值)。例如,this compiles。 -
是的,在其他渠道找到了这个解决方案,谢谢!回答我自己的问题。
标签: rust json-deserialization lifetime serde