如何在不引起内存泄漏的情况下从 serde_json::from_slice 修复 "borrowed value does not live long enough"?
How do I fix "borrowed value does not live long enough" from serde_json::from_slice without incurring a memory leak?
考虑以下代码:
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()
反而可行,但我不确定这是正确的解决方案:该方法的文档叙述:
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
一旦函数结束,返回的引用就会被丢弃。
问题
如何在不引起内存泄漏的情况下解决上述问题?
use serde::de::DeserializeOwned;
pub async fn parse_bytes<R: DeserializeOwned>(_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")
}
考虑以下代码:
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()
反而可行,但我不确定这是正确的解决方案:该方法的文档叙述:
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
一旦函数结束,返回的引用就会被丢弃。
问题
如何在不引起内存泄漏的情况下解决上述问题?
use serde::de::DeserializeOwned;
pub async fn parse_bytes<R: DeserializeOwned>(_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")
}