Terry T
Terry T

Reputation: 119

Dispatching Rust TcpStream from TcpListener to separate method in loop

I'm new to Rust and have the following code:

while let Some(tcp_stream) = incoming.next() {
    match tcp_stream {
        Ok(s) => {
            handle_request(tcp_stream.unwrap(), &routes);
        }
        Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
            continue;
        }
        Err(e) => panic!("Error"),
    };
}

And I get the following error:

use of moved value: `tcp_stream`

value used here after partial move

note: move occurs because value has type `std::net::TcpStream`, which does not implement the `Copy` trait rustc(E0382)
lib.rs(72, 20): value moved here
lib.rs(73, 36): value used here after partial move

What I'm looking to do is handle the new connection/TcpStream in a separate method handle_request but I'm unsure how to go about doing this. Passing a reference gives the same issue. I tried implementing the Copy trait for TcpStream but since I'm outside of its crate I can't seem to do that.

Any pointers would be greatly appreciated!

Upvotes: 0

Views: 472

Answers (1)

Gurwinder Singh
Gurwinder Singh

Reputation: 39487

One fix is to perform error checking in one arm:

async fn listen(self, listener: TcpListener) {
    let routes = self.routes;
    let mut incoming = listener.incoming();
    while let Some(tcp_stream) = incoming.next() {
        match tcp_stream {
            Ok(s) => {
                handle_request(tcp_stream.unwrap(), &routes);
            }
            Err(e) => {
                if e.kind() == io::ErrorKind::WouldBlock {
                    continue;
                }
                panic!("Error");
            },
        };
    }
}

Upvotes: 1

Related Questions