I would like to write a function that accepts an integer, and spawns threads that use this integer. The integer could be computed. It doesn't need to be a literal. If I use a concrete type such as usize
, it would work but when I try to generalize it, it fails to compile:
fn g<A>(a: A)
where
A: num::PrimInt + Copy + std::fmt::Debug + Send,
{
let hs = (0..3).map(|_| {
std::thread::spawn(move || {
println!("{:?}", a);
})
});
for h in hs {
h.join().unwrap();
}
}
The error is:
1 | fn g<A>(a: A)
| - help: consider adding an explicit lifetime bound `A: 'static`...
...
6 | std::thread::spawn(move || {
| ^^^^^^^^^^^^^^^^^^
|
note: ...so that the type `[closure@src/main.rs:6:28: 8:10 a:A]` will meet its required lifetime bounds
--> src/main.rs:6:9
|
6 | std::thread::spawn(move || {
| ^^^^^^^^^^^^^^^^^^
Since I have the Copy
trait, it should be able to copy this value for each thread and hence the lifetime bound recommendation is not necessary. How do I resolve this?