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
Two
Three
".into();
let k : Vec<String> = s.split("
").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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…