0

How can I specify lifetimes in a for loop? I'm trying to multithread ports, but keep running into lifetime issues.

pub fn connect_server(&self) {
        for x in 58350..58360 {
            thread::spawn(|| {                                 
                match TcpListener::bind(self.local_ip.to_string() + &x.to_string()) {
                    Ok(socket) => {
                        for stream in socket.accept() {
                            println!("received packet: {:?}", stream);
                        }
                    },
                    Err(error) => panic!("Failed to connect socket: {}", error)
                }
            });

            thread::sleep(Duration::from_millis(1));
        }
    }

error:

borrowed data escapes outside of associated function
`self` escapes the associated function body here
paspielka
  • 15
  • 3
  • You could call `self.local_ip.to_string()` outside of the loop and assign it to a local variable; does that help? – kaya3 Nov 09 '22 at 21:30

1 Answers1

0

Generate the bind address outside the thread::spawn closure, and use a move closure rather than capturing by reference:

    pub fn connect_server(&self) {
        for x in 58350..58360 {
            let bind_address = format!("{}{}", self.local_ip, x);
            thread::spawn(move || {                                 
                match TcpListener::bind(bind_address) {
                    Ok(socket) => {
                        for stream in socket.accept() {
                            println!("received packet: {:?}", stream);
                        }
                    },
                    Err(error) => panic!("Failed to connect socket: {}", error)
                }
            });

            thread::sleep(Duration::from_millis(1));
        }
    }
PitaJ
  • 12,969
  • 6
  • 36
  • 55