Borrowing solution using Rc/RefCell?

Hi!

I have a question regarding borrowing.

The following program will not compile because stream is being moved when I create the BuffReader.

I later want to use the stream to use the write_all method on the stream, which I cannot since it has been moved.

I can pass a reference to BuffReader but this will not work as the write_all requires a mutable reference.

What is the proper way to solve this using Rc and RefCell?

use std::net::{
    TcpListener, 
    TcpStream
};
use std::thread;
use std::io::{
    BufReader,
    BufRead,
    Write,
};

fn handle_client(mut stream: TcpStream) {
    let reader = BufReader::new(stream);
    let mut lines = reader.lines();

    while let Some(line) = lines.next() {
        let line = line.unwrap();
        stream.write_all(line.as_bytes()).unwrap();
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    // accept connections and process them serially
    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(move || {
            handle_client(stream);
        });
    }
}```

&TcpStream (note the reference) implements Read and Write, so you can do:

-fn handle_client(mut stream: TcpStream) {
-    let reader = BufReader::new(stream);
+fn handle_client(stream: TcpStream) {
+    let reader = BufReader::new(&stream);
+    let mut writer = &stream;
     let mut lines = reader.lines();

     while let Some(line) = lines.next() {
         let line = line.unwrap();
-        stream.write_all(line.as_bytes()).unwrap();
+        writer.write_all(line.as_bytes()).unwrap();
     }
 }

Playground.

1 Like

Thanks!

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.