我是 Rust 新手,并尝试通过围绕它创建一些东西来学习该语言。
面对这个问题,
self
在此函数内有效,但闭包是async
,因此它可能会在此函数的生命周期之后执行,并且闭包捕获self
。我明白了问题所在。但我该怎么办呢?我明白这与寿命有关。但有人能告诉我解决方案是什么吗?
pub async fn run(&mut self) -> Result<i32, &str> {
.
.
.
match server.accept().await {
Ok(p) => {
tokio::spawn(async {
self.handle_temp_connection(p)
});
},
Err(err) => {
println!("Some problem accepting a connection.")
}
}
}
fn handle_temp_connection(&self, p_socket_addr: (TcpStream, SocketAddr)) {
...
}
错误:
error[E0521]: borrowed data escapes outside of associated function
--> src/app.rs:34:21
|
20 | pub async fn run(&mut self) -> Result<i32, &str> {
| ---------
| |
| `self` is a reference that is only valid in the associated function body
| let's call the lifetime of this reference `'1`
...
34 | / tokio::spawn(async {
35 | | self.handle_temp_connection(p)
36 | | });
| | ^
| | |
| |______________________`self` escapes the associated function body here
| argument requires that `'1` must outlive `'static`