I am new to rust and tokio async, and I am trying to compile the following seemingly straightforward code:
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?
}
But the compiler complains:
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 {
| ^^^^^^^^^^^^^^^^^
From the previous discussions and examples I have found on the subject, I understand that passing a reference to network_config to the spawn-ed closure would cause lifetime problems since the separate thread may outlive network_config. This is why I am moving a clone of network_config to the spawned thread, but there still seems to be a lifetime ambiguity.
Is there any extra hint I could give the compiler so that it correctly gets the lifetimes ? Or am I doing the whole thing wrong ?
Note: the NetworkConfig class is defined as:
#[derive(Debug, Deserialize)]
pub struct NetworkConfig {
pub bind: String,
pub node_key_file: String,
}
See Question&Answers more detail:os