我对rust和tokio异步是陌生的,我正在尝试编译以下看似简单的代码:
async fn network_handler(network_config: &config::NetworkConfig) -> Result<(), Error> { Ok(()) } pub async fn run(network_config: &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 | pub async fn run(network_config: &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 | pub async fn run(network_config: &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的副本移至生成的线程,但是似乎仍然存在生命周期歧义的原因。
我是否可以提供编译器任何其他提示,以使其正确获得生存期?还是我整个事情做错了?
注意:NetworkConfig类定义为:
#[derive(Debug, Deserialize)]
pub struct NetworkConfig {
pub bind: String,
pub node_key_file: String,
}
我不熟悉rust和tokio异步,我正在尝试编译以下看似简单的代码:async fn network_handler(network_config:&config :: NetworkConfig)->结果
如果要克隆NetworkConfig
值,请为其声明Clone
特性: