rust for循环中的生存期

oxiaedzo  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(177)

如何在for循环中指定生存期?我尝试对端口进行多线程处理,但总是遇到生存期问题。

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

错误:

borrowed data escapes outside of associated function
`self` escapes the associated function body here
ev7lccsx

ev7lccsx1#

thread::spawn闭包外部生成绑定地址,并使用move闭包而不是通过引用捕获:

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

相关问题