简体   繁体   English

当使用将在函数末尾删除的String调用时,如何返回serde_json :: from_str的结果?

[英]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: 惯用的解决方案是:

  • having T implement DeserializeOwned instead, T实现DeserializeOwned
  • have two methods: one to create the string, and one to deserialize, and ensure that the deserialized result is stored longer than T . 有两种方法:一种创建字符串,另一种进行反序列化,并确保反序列化的结果存储的时间长于T

The former is, of course, much easier. 当然,前者要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法从调用的函数返回更新的字符串并释放内存 - unable to return the updated string from called function and free the memory 如何从 function 返回一个字符串? - How do I return a string from a function? 字符串类中c_str函数的内存分配 - memory allocation for c_str function in string class 从Java和Python调用本机库时如何释放内存? - How is memory freed when native libraries are called from Java and Python? 我该如何在C库中返回二元运算函数的结果? - How should I return the result of a binary-operation function in a C library? 当调用string intern()方法时 - when string intern() method is getting called 在方法结束时返回nil或boolean比让Ruby返回最后一行代码的结果更高效吗? - Is returning nil or a boolean at the end of a method more performant than letting Ruby return the result of the last line of code? std :: string :: c_str()覆盖了函数返回的前一个 - std::string::c_str() overwrittes the previous one returned by a function 为什么析构函数不是从函数中调用返回的对象? - Why is the destructor not called for the returned object from the function? 当我们从`using'块中的方法返回时,如何处理内存? - How is memory handled when we return from a method in a `using` block?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM