The following code attempts to asynchronously read from a TCP socket. It compiles, but it follows an unidiomatic pattern regarding ownership. Identify the issue.

Go & Rust interview question for Advanced practice.

Answer

The function takes ownership of stream, but only gives a borrow to BufReader, preventing the BufReader from outliving the function scope. BufReader::new(stream) should be used to move ownership.

Explanation

The function readdata takes ownership of the TcpStream. However, BufReader::new(&stream) only creates a reader over a borrow of the stream. This creates a lifetime dependency: the BufReader cannot outlive the stream variable within the readdata function. The idiomatic pattern is to move the owned stream into the BufReader by calling BufReader::new(stream). This makes the BufReader the new owner of the stream resource and allows it to be used more flexibly, such as being returned from the function.

Related Questions