![](/img/trans.png)
[英]unable to return the updated string from called function and free the memory
[英]How to return the result of serde_json::from_str when called with a String that will be dropped at the end of the function?
我在函數內部有一個新分配的String
,我需要創建一個派生對象,該派生對象從該String
中借用&str
並返回給定的對象。
我知道我的代碼是錯誤的,因為String
生存期就是函數的生存期,因此派生的對象將永遠不會由於懸掛引用而返回。
這里的慣用解決方案是什么? 我無法更改serde_json::from_str
的簽名
#[inline]
pub fn get_object<'a, T>(json_data: &'a Value, path: &[&str]) -> Option<T>
where T: serde::Deserialize<'a>
{
let mut pointer_str = String::new();
for entry in path.iter() {
pointer_str = format!("{}/{}", pointer_str, entry);
}
let child = json_data.pointer(&pointer_str).unwrap().to_string();
let result = serde_json::from_str(&child).ok();
return result;
}
錯誤:
error: `child` does not live long enough
--> src/lib.rs:88:40
|
88 | let result = serde_json::from_str(&child).ok();
| ^^^^^ does not live long enough
89 | return result;
90 | }
| - borrowed value only lives until here
慣用的解決方案是:
T
實現DeserializeOwned
, T
當然,前者要容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.