Hi!
I'm writing a quick test and I'm met with the following. The code has been modified to get the problem across (the actual test is slightly more complex):
#[test]
fn internal_test() {
let mock_data = vec![5, 1, 2];
let num_threads = 25;
let num_iterations = mock_data.len();
let mut handles = vec![];
for _ in 0..num_threads {
let handle: thread::JoinHandle<()> = thread::spawn( || {
for j in 0..num_iterations {
print!( "{}", mock_data[j] );
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
Now the compiler naturally complains:
closure may outlive the current function, but it borrows `num_iterations`, which is owned by the current function may outlive borrowed value `num_iterations`
closure may outlive the current function, but it borrows `mock_data`, which is owned by the current function may outlive borrowed value `mock_data`
The num_iterations
one can be fixed by adding move
to the enclosure. However not the mock_data one:
use of moved value: `mock_data`
value moved into closure here, in previous iteration of loop
Note: There's other more complex structures I left out of this example that have the same problem as mock_data.
Normally Arc would have to be used. But the thing is; in this case I don't care. I know that the variables in the enclosure won't outlive the main function. The enclosure stops in handle.join().unwrap();
.
Is there a way to tell Rust of that? I suspect lifetime annotations could fix this but I can't figure out the right syntax. I don't mind using unsafe in this scenario either.
Cheers and thanks in advance!