If BufReader takes ownership of a stream, how can I read and write lines on it?

Solution: use references.

let mut stream = ...;
let reader = BufReader::new(&stream);
let writer = BufWriter::new(&stream);

Explanation

If we take a closer look at BufReader::new, we see that it takes an argument inner of type R, where R is just any type that implements Read:

impl<R: Read> BufReader<R> {
    pub fn new(inner: R) -> BufReader<R> { ... }
}

We then take a look at Read and see this implementation:

impl<'a> Read for &'a TcpStream

So we can just pass a reference to the new function, like so:

let reader = BufReader::new(&stream);

We will do the same for BufWriter and Write and will see that indeed there is this implementation:

impl<'a> Write for &'a TcpStream

So we can, again, use an immutable reference to create the BufWriter.

Leave a Comment