-3

I have the following code:

let mut v2: Value;
let mut ts = v["response"]["ts"].as_str().unwrap();

...

loop {

        v2 = longpoll_question(server.clone(),ts,key.clone());
        if v2["ts"].as_str() == None {
            continue;
        }
        ts = v2["ts"].as_str().unwrap();

...

}

Here I am getting a response from server which is in JSON format, and then retrieving a "ts" value from it that is needed for the next request to the server. Sometimes the value returned by server is "None" (presumably, network issues or remote API problems) and that was causing a crash, so I decided to check whether the value is None before unwrapping. This, however, refuses to compile with E0506 and I have no idea why. Could you please explain?

danshat
  • 25
  • 9
  • 1
    Please show us the full error message, and ideally code to reproduce the problem. With the information given, this is hard to answer. – Sven Marnach Oct 22 '21 at 15:34
  • We don't have enough information. What is `v` ? What is the type `Value` ? Where is the value dropped and where is the use after drop ? IMO, the solution would be to give the ownership of `v2`'s content to `ts`, but I don't have enough information to be sure it's the good solution – Naeio Oct 22 '21 at 18:10
  • I asked a concise Question for common rust error `error[E0716]` [error E0716: temporary value dropped while borrowed (rust)](https://stackoverflow.com/questions/71626083/error-e0716-temporary-value-dropped-while-borrowed-rust). It links back to this Question. – JamesThomasMoon Mar 26 '22 at 07:26

1 Answers1

0

I managed to fix this by changing type of ts to String and using to_string(). I think ts, being an &str, was a reference to data of v2, so it was impossible to drop v2 without also dropping ts.

danshat
  • 25
  • 9
  • 1
    Yup, and this implies that the whole string is copied elsewhere and thus duplicated. It's easy and great if you don't particularly need good performances, but is quite bad if you need to have really high perfs – Naeio Oct 22 '21 at 18:06
  • _If_ your `Value` is actually a [`json::JsonValue`](https://docs.rs/json/0.12.4/json/enum.JsonValue.html), then it's probably better to use [`take_string`](https://docs.rs/json/0.12.4/json/enum.JsonValue.html#method.take_string) to avoid the unnecessary allocation and copy. – Jmb Oct 25 '21 at 06:39