且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

延长线程变量的生命周期

更新时间:2023-01-25 17:21:20

从根本上讲,问题是lines的借用片段.在这里您实际上无能为力,因为无法保证每个line都不会超过s本身.

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.

另外,要清楚一点:Rust中绝对没有办法 延长变量的生命周期".根本做不到.

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

解决此问题的最简单方法是从被借用的line变为拥有的 .像这样:

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);
        });
    }
}

.map(|s| s.into())&str转换为String.由于String拥有其内容,因此可以安全地将其移动到每个线程的闭包中,并且独立于创建它的线程而存在.

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.

注意:您可以使用新的作用域线程API在每晚Rust中执行此操作,但这仍然不稳定.

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