Serde deserialisation lifetime confusion

Hello, I'm having a hard time solving what I think should be a simple problem. I have an async_std::net::TcpStream which I'm expecting some JSON data from. I have a function

async fn recv_str(stream: &mut TcpStream) -> Result<String>

which will wait until there's some data to become available from the stream and read it into a string.

When I try to deserialise that string using

let data: Vec<(DsKey, DsValue)> = serde_json::from_str(&data_str)?

I'm running up against data_str not living long enough, and from_str insisting that it be borrowed for 'static. I'm not sure how to deal with this, would appreciate any advice!

Whole code for reference:

let mut stream = ... // connecting to the TcpStream itself

// Initialise the telemetry store so that no old data is kept around
telem_store = TelemStore::new();
        
// Main operating loop
loop {
    // Recieve data from the server, in a timeout
    let data_str: String = match future::timeout(
        read_timeout_dur, 
        recv_str(&mut stream)
    ).await {
        // No timeout, propagate any recieve errors
        Ok(s) => s?,
        // Timeout, disconnected, break out of main loop
        Err(_) => {
            println!("No data recieved for {} s, assuming disconnect \
                from server", READ_TIMEOUT_S);
            break
        }
    };

    // Parse the data into a vector of keys and values
    let data: Vec<(DsKey, DsValue)> = serde_json::from_str(&data_str)
        .wrap_err("Error parsing data from the server")?;

     // Update items in the data store
    telem_store.update(data);            
}

And the error:

error[E0597]: `data_str` does not live long enough
   --> src/bin/text_telem.rs:203:69
    |
203 |             let data: Vec<(DsKey, DsValue)> = rson_rs::de::from_str(&data_str)
    |                                               ----------------------^^^^^^^^^-
    |                                               |                     |
    |                                               |                     borrowed value does not live long enough
    |                                               argument requires that `data_str` is borrowed for `'static`
...
208 |         }
    |         - `data_str` dropped here while still borrowed


Is it possible that DsKey or DsValue have lifetimes that are bound by data_str?
You may have to create an owned version of the deserialized structs

Yes I'm incredibly stupid, after I posted I went back and checked over them and one of the variants of DsValue wraps a &'static str, changing this to

enum DsValue<'a> {
    Str(&'a str)
    ...
}

solved the issue.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.