简体   繁体   中英

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.

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.

What would be the idiomatic solution here? I cannot change the signature of 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,
  • have two methods: one to create the string, and one to deserialize, and ensure that the deserialized result is stored longer than T .

The former is, of course, much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM