rustlifetimeborrow-checker

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

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();

    serde_json::from_str(&child).ok()
}

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

Solution

  • The idiomatic solution is either of:

    The former is, of course, much easier.