Simple code that demonstrate my problem:
use std::thread;
fn main() {
let data1 = vec!["1","2","3","4","5",];
let data2 = vec!["a","b","c","d","e",];
let mut h = Vec::new();
for (i, j) in data1.iter().zip(data2.iter()) {
let tmp = thread::spawn(move || {
println!("{} {}", i, j);
});
h.push(tmp);
}
for jh in h.into_iter() {
jh.join().unwrap();
}
}
Error:
Compiling playground v0.0.1 (/playground)
error[E0597]: `data1` does not live long enough
--> src/main.rs:8:19
|
8 | for (i, j) in data1.iter().zip(data2.iter()) {
| ^^^^^^^^^^^^ borrowed value does not live long enough
9 | let tmp = thread::spawn(move || {
| ___________________-
10 | | println!("{} {}", i, j);
11 | | });
| |__________- argument requires that `data1` is borrowed for `'static`
...
17 | }
| - `data1` dropped here while still borrowed
error[E0597]: `data2` does not live long enough
--> src/main.rs:8:36
|
8 | for (i, j) in data1.iter().zip(data2.iter()) {
| ^^^^^^^^^^^^ borrowed value does not live long enough
9 | let tmp = thread::spawn(move || {
| ___________________-
10 | | println!("{} {}", i, j);
11 | | });
| |__________- argument requires that `data2` is borrowed for `'static`
...
17 | }
| - `data2` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to 2 previous errors
If I understand correctly problem is that complier does not know that my data1 and data2, live till the end of program ? That is why it is requiring that data1 and data2 need to be 'static. But what is confusing to me is that it know that data1 and data2 will be dropped at line 17, what is end of program. Maybe it is confused because I use threads and it does not know that I do join() on threads ?
Anyway any ideas how to solve it ?