Object doesn't live long enough, but why does it need to?

⚓ Rust    📅 2026-02-15    👤 surdeus    👁️ 6      

surdeus

Hi rustceans,

I'm learning rust by playing a bit by building a small server over TCP. I'm using JSON as serde data format. I have a simple generic function read_request as follow:

struct Server;
impl<'a> Server {

   [...]

   fn read_request<T>(stream: &TcpStream) -> T
   where
       T: Deserialize<'a>
   {
        let mut reader = std::io::BufReader(stream);
        let raw_request = reader.fill_buf().expect("reading failed").to_vec();
        serde_json::from_slice(&raw_request).expect("couldn't parse request")
    }
}

As you may have guessed, raw_request doesn't outlive lifetime 'a and to make this work (I believe) I would need to somehow allocate the raw_request in the same (or the above) scope as the Server object. But isn't there a simpler way? And also why does serde_json need to keep raw_request alive even after read_request has returned? Isn't it creating an object of T with freshly allocated data?

cheers

3 posts - 2 participants

Read full topic

🏷️ Rust_feed