如何解决“借用的价值寿命不够长”的问题from serde_json::from_slice 不会导致内存泄漏?
考虑以下代码片段:
pub async fn parse_bytes<'a, R: Deserialize<'a>>(_query: serde_json::Value) -> R {
let result: Vec<u8> = vec![]; // fetch_result(&query).await
serde_json::from_slice::<R>(result.as_slice())
.expect("Can't parse bytes response")
}
错误
它无法编译:
`result` does not live long enough
borrowed value does not live long enough
暂定解决方案
提供 result.leak()
可以,但我不确定这是正确的解决方案:该方法的文档叙述:
此函数主要对于在程序剩余生命周期中存在的数据有用。删除返回的引用将导致内存泄漏
,并且一旦函数结束,返回的引用就会被删除。
问题
如何解决上述问题而不引起内存泄漏?
Consider the following piece of code:
pub async fn parse_bytes<'a, R: Deserialize<'a>>(_query: serde_json::Value) -> R {
let result: Vec<u8> = vec![]; // fetch_result(&query).await
serde_json::from_slice::<R>(result.as_slice())
.expect("Can't parse bytes response")
}
Error
It doesn't compile:
`result` does not live long enough
borrowed value does not live long enough
Tentative solution
Providing result.leak()
instead works, but I'm not sure it's the right solution: the method's documentation recites:
This function is mainly useful for data that lives for the remainder of the program's life. Dropping the returned reference will cause a memory leak
And the returned reference is dropped as soon as the function ends.
Question
How do I fix the above without incurring a memory leak?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请改用
DeserializeOwned
。Use
DeserializeOwned
instead.