我正在尝试编译下面看似简单的代码,但是出现了错误:
use std::io::Error;
#[derive(Debug)]
struct NetworkConfig {
bind: String,
node_key_file: String,
}
async fn network_handler(network_config: &NetworkConfig) -> Result<(), Error> {
Ok(())
}
async fn run(network_config: &NetworkConfig) -> Result<(), Error> {
let network_config_copy = network_config.clone();
tokio::spawn(async move {
network_handler(&network_config_copy).await
}).await?
}
error: cannot infer an appropriate lifetime
--> src/network.rs:43:18
|
43 | async fn run(network_config: &NetworkConfig) -> Result<(), Error> {
| ^^^^^^^^^^^^^^ ...but this borrow...
44 | let network_config_copy = network_config.clone();
45 | tokio::spawn(async move {
| ------------ this return type evaluates to the `'static` lifetime...
|
note: ...can't outlive the lifetime `'_` as defined on the function body at 43:34
--> src/network.rs:43:34
|
43 | async fn run(network_config: &NetworkConfig) -> Result<(), Error> {
| ^
help: you can add a constraint to the return type to make it last less than `'static` and match the lifetime `'_` as defined on the function body at 43:34
|
45 | tokio::spawn + '_(async move {
| ^^^^^^^^^^^^^^^^^
根据以前对这个主题的讨论和例子,我理解将 network_config
的引用传递给生成的闭包会导致生存期问题,因为单独的线程可能会超过 network_config
的生命周期。这就是为什么我正在将 network_config
的克隆移动到生成的线程中,但似乎仍然存在生命周期的不确定性。
是否有任何额外的提示可以给编译器,以便它正确获取生命周期?或者我整个做法都是错误的?