我希望您能将
self
结构体对象传递到线程中,然后调用它的time_tick()
方法以增加HMS时间。pub fn start(&mut self) {
self.acti = true; // the time tick is activated now...
thread::spawn(move || {
let local_self: *mut Self = self; // this self live in the thread
loop {
thread::sleep(Duration::from_secs(1)); // wait for 1 sec
if (*local_self).acti == true { (*local_self).time_tick(); }
(*local_self).print_time(); // for debug
}
});
}
我收到了这个错误信息:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/hmstimer/mod.rs:42:17
|
42 | thread::spawn(move || {
| _______________________^
43 | | let local_self: *mut Self = self; // this self live in the thread
44 | | loop {
45 | | thread::sleep(Duration::from_secs(1)); // wait for 1 sec
... |
48 | | }
49 | | });
| |_________^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 40:2...
--> src/hmstimer/mod.rs:40:2
|
40 | pub fn start(&mut self) {
| _____^
41 | | self.acti = true; // the time tick is activated now...
42 | | thread::spawn(move || {
43 | | let local_self: *mut Self = self; // this self live in the thread
... |
49 | | });
50 | | }
| |_____^
= note: ...so that the types are compatible:
expected &mut hmstimer::HMSTimer
found &mut hmstimer::HMSTimer
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/hmstimer/mod.rs:42:17: 49:7 self:&mut hmstimer::HMSTimer]` will meet its required lifetime bounds
但是看起来关于方法似乎不合适。有什么最佳实践来完成这个任务吗?
self
的无限线程。当self
被销毁时,你期望它会做什么?这就是为什么Rust禁止这样做的完美理由。 - mcartonlocal_self
怎么样?但是我的定义似乎不正确... - Casperself
的类型是&mut Self
,所以&mut self
的类型是&mut &mut Self
。错误信息应该很明显,所以请在问题中始终包含它。然而,修复类型问题并不能解决@mcarton提到的生命周期问题。 - Sven Marnachif (*local_self).acti == true
— 这是多余的。只需使用if local_self.acti
。同样适用于local_self.time_tick()
和local_self.print_time()
。 - Shepmaster