I am new to multithreaded programming and I am unable to execute following code:
use std::thread;
struct Test;
impl Test {
pub fn foo(&self) {
for i in 0..5 {
thread::spawn(|| { self.bar(); });
}
}
pub fn bar(&self) {
println!("bar");
}
}
fn main() {
let t = Test{};
t.foo()
}
I receive following error:
selfhas an anonymous lifetime'_but it needs to satisfy a'staticlifetime requirement
I am assuming this happens because thread does not know if the object self refers to does not get deleted during the execution of the thread. Is there any way to somehow execute this code? Or do I need my methods to have static lifetimes? (if such thing is even possible)
Here is the playground link.