如何在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
1条答案
按热度按时间ev7lccsx1#
在
thread::spawn
闭包外部生成绑定地址,并使用move
闭包而不是通过引用捕获: