如何在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
在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));
}
}