[英]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?
I have a newly allocated String
inside a function, I need to create a derived object that borrows &str
from that String
, and return the given object. 我在函数内部有一个新分配的
String
,我需要创建一个派生对象,该派生对象从该String
中借用&str
并返回给定的对象。
I know my code is wrong because the String
lifetime is that of the function, so the derived object will never be returned because of dangling references. 我知道我的代码是错误的,因为
String
生存期就是函数的生存期,因此派生的对象将永远不会由于悬挂引用而返回。
What would be the idiomatic solution here? 这里的惯用解决方案是什么? I cannot change the signature of
serde_json::from_str
我无法更改
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;
}
And the error: 错误:
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
The idiomatic solution is either of: 惯用的解决方案是:
T
implement DeserializeOwned
instead, T
实现DeserializeOwned
, T
. T
The former is, of course, much easier. 当然,前者要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.