Extend lifetime of a variable for thread

▼魔方 西西 提交于 2019-11-29 16:17:28

The problem, fundamentally, is that line is a borrowed slice into s. There's really nothing you can do here, since there's no way to guarantee that each line will not outlive s itself.

Also, just to be clear: there is absolutely no way in Rust to "extend the lifetime of a variable". It simply cannot be done.

The simplest way around this is to go from line being borrowed to owned. Like so:

use std::thread;
fn main() {
    let mut s: String = "One\nTwo\nThree\n".into();
    let k : Vec<String> = s.split("\n").map(|s| s.into()).collect();
    for line in k {
        thread::spawn(move || {
            println!("nL: {:?}", line);
        });
    }
}

The .map(|s| s.into()) converts from &str to String. Since a String owns its contents, it can be safely moved into each thread's closure, and will live independently of the thread that created it.

Note: you could do this in nightly Rust using the new scoped thread API, but that is still unstable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!