I am reading a string from a file, splitting it by lines into a vector and then I want to do something with the extracted lines in separate threads. Like this:
use std::fs::File;
use std::io::prelude::*;
use std::thread;
fn main() {
match File::open("data") {
Ok(mut result) => {
let mut s = String::new();
result.read_to_string(&mut s);
let k : Vec<_> = s.split("
").collect();
for line in k {
thread::spawn(move || {
println!("nL: {:?}", line);
});
}
}
Err(err) => {
println!("Error {:?}",err);
}
}
}
Of course this throws an error, because s
will go out of scope before the threads are started:
s` does not live long enough
main.rs:9 let k : Vec<_> = s.split("
").collect();
^
What can I do now? I've tried many things like Box
or Arc
, but I couldn't get it working. I somehow need to create a copy of s
which also lives in the threads. But how do I do that?