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);
});
}
}```