0

I want to implement TCP client using struct:

use std::error::Error;

use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
use std::io::Read;

const CLIENT: Token = Token(0);

pub struct Client {
    pub connected: bool,
    connection: Option<TcpStream>,
}

impl Client {
    pub fn connect(&mut self, host: &str, port: i16) {
        let addr = format!("{}:{}", host, port).parse().unwrap();

        if let Ok(stream) = TcpStream::connect(addr) {
            self.connected = true;
            self.connection = Some(stream);
        } else {
            println!("Cannot connect !");
        }
    }

    pub fn listen(&mut self) {
        let mut connection = self.connection.unwrap();
        let mut poll = Poll::new().unwrap();
        let mut events = Events::with_capacity(256);

        poll.registry().register(
            &mut connection,
            CLIENT,
            Interest::READABLE | Interest::WRITABLE
        );

        loop {
            // ...
        }
    }

    pub fn new() -> Client {
        Client {
            connected: false,
            connection: None,
        }
    }
}

But I got an error:

let mut connection = self.connection.unwrap();
                     ^^^^^^^^^^^^^^^ move occurs because `self.connection` has type `Option<mio::net::TcpStream>`, which does not implement the `Copy` trait

How can I fix this ?

Sergio Ivanuzzo
  • 1,820
  • 4
  • 29
  • 59
  • 2
    consider `self.connection.as_mut().unwrap()` to access the `mio::netTcpStream` reference rather than the value and take the reference later – joshmeranda Jan 25 '22 at 03:02
  • 1
    @joshmeranda very thank you ! it works. If you add your comment as answer, I will accept. Thanks a lot. – Sergio Ivanuzzo Jan 25 '22 at 03:09

0 Answers0