我希望在结构“消失”后停止一个线程:
use std::thread;
struct Foo {
handle: thread::JoinHandle<()>,
}
impl Drop for Foo {
fn drop(&mut self) {
println!("we drop data");
self.handle.join();
}
}
fn main() {
let handle = thread::spawn(|| println!("hi from thread"));
let _ = Foo { handle: handle };
}
但它没有编译:
error[E0509]: cannot move out of type `Foo`, which implements the `Drop` trait
--> src/main.rs:10:9
|
10 | self.handle.join();
| ^^^^^^^^^^^ cannot move out of here
这是因为join
需要self
,而不是&mut self
。如何在drop
方法中加入此主题?