我想写一个包装函数来读取一个包含有 Vec[u8]
(其实只是MsgPacks)并将它们转换为原生锈结构,我的代码看起来像这样。
use rmp_serde::{decode, from_slice};
use serde::Deserialize;
#[derive(Debug)]
pub enum MsgPackParseErr {
ParseIntError,
SerdeError,
}
impl From<std::num::ParseIntError> for MsgPackParseErr {
fn from(_e: std::num::ParseIntError) -> Self {
return Self::ParseIntError;
}
}
impl From<decode::Error> for MsgPackParseErr {
fn from(_e: decode::Error) -> Self {
return Self::SerdeError;
}
}
pub fn msgpack_from_byte_string<'b, T>(raw: String) -> Result<T, MsgPackParseErr>
where
T: Deserialize<'b>,
{
let parsing_string: Result<Vec<u8>, _> = raw.split(" ").map(|x| x.parse()).collect();
let parsed_string = parsing_string?;
let parsing_obj = from_slice(&parsed_string);
Ok(parsing_obj?)
}
但我得到的错误信息是
temporary value dropped while borrowed
creates a temporary which is freed while still in use
对于第23至28行,即
let parsing_obj = from_slice(&parsed_string);
Ok(parsing_obj?)
我不知道我做错了什么......
你的错误来自于以下事实 T: Deserialize<'b>
在你的代码中,约束T只能活到寿命'b,这又意味着无论from_slice的输入是什么,它都不能超过寿命(否则就会出现使用后自由的错误)。
pub fn msgpack_from_byte_string<'b, T>(raw: String) -> Result<T, MsgPackParseErr>
where
T: Deserialize<'b>
那么,为什么你的序列化对象不能比与之相关的数据活得更久呢?如果可能的话,serde通过直接引用输入缓冲区来避免输入数据的复制和额外字段的分配。这一点在serde手册中关于以下章节也有详细的解释 寿命.请注意,serde还有其他特性,可能更适合你的用例,并且不受限于输入的寿命(例如,DeserializeOwned)。