Borrowed value does not live long enough string split threads

I have searched and searched and none of what I've found applies even though superficially it looks like it should. Hopefully someone can help me keep my head from exploding.

Error:

`parts` does not live long enough
borrowed value does not live long enough

I am trying to use a string, split it and then use the pieces later in a loop. I know the error has something to do with the tokio::spawn, because if I remove that, then the errors go away, but I can't figure out what's causing the error.

let mut v4ips:Vec<Ifv4Addr> = Vec::new();
for ip in v4ips{
    let parts = ip.ip.to_string();
    if ip.netmask.to_string()==class_c{
        let p :Vec<&str>=parts.split(".").collect();
        for address in 0..255{
            let v=p.clone();
            let ip = ip.clone();
            tokio::spawn(async move{
                let stream = TcpStream::connect(format!("{}{}{}{}:{}",v[0],v[1],v[2],v[3],"2500")).await;
                match stream{
                    Ok(a)=>{d.push(ip.clone())},
                    Err(e)=>{}
                }
            }
        }
    }
}

Please post the full error as reported by cargo build or cargo check. The errors reported by IDEs are often incomplete and missing useful informations or other hints.

92 | let p :Vec<&str>=parts.split(".").collect();
| ^^^^^-----------
| |
| borrowed value does not live long enough
| argument requires that parts is borrowed for 'static
...
116 | }
| - parts dropped here while still borrowed

You need to clone the strings if you want to be able to move them into the new task. Currently you have a vector of &str, which means that the vector elements are references to the parts variable. Cloning the vector doesn't help because that just yields another Vec<&str>, also with references to parts.

In this case the easiest would be to just move the format! call outside the spawned task.

That actually makes sense, I wasn't thinking in terms of the reference to the strings, but about the Vec. Thanks!!!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.