I want to create a thread inside of the new
method and stop it after the struct is destroyed:
use std::thread;
struct Foo {
handle: thread::JoinHandle<()>,
}
impl Foo {
pub fn new(name: &str) -> Foo {
let name = name.to_string();
Foo {
handle: thread::spawn(move || {
println!("hi {}", name);
}),
}
}
pub fn stop(&mut self) {
self.handle.join();
}
}
fn main() {
let mut foo = Foo::new("test");
foo.stop();
}
This doesn't compile, and I can not understand why:
error[E0507]: cannot move out of borrowed content
--> <anon>:15:9
|
15 | self.handle.join();
| ^^^^ cannot move out of borrowed content
And in newer versions of Rust:
error[E0507]: cannot move out of `self.handle` which is behind a mutable reference
--> src/main.rs:17:9
|
17 | self.handle.join();
| ^^^^^^^^^^^ move occurs because `self.handle` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait
How can I fix this error?
In the future, I will implement Drop
for Foo
, and will call stop()
from drop()
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…