Option<JoinHandle> is un-joinable


This ought to be simple, but I can't get it to compile.

I have an Option, because I have a struct which may optionally own a spawned thread. I can create this easily enough, but when it comes time to join, that's not possible. Tried:

    let status = self.child_thread.unwrap().join();

    let status = self.child_thread.as_ref().unwrap().join();

    let status = &self.child_thread.as_ref().unwrap().join();

also, boxing the JoinHandle. No good.

The problem is that JoinHandle is neither copyable nor cloneable, or here, moveable. So I can't get it out of the Option, and while inside the Option, I can't apply .join() to it.

I'm probably missing something obvious here.

You want to use Option::take:

let status = self.child_thread.take().unwrap().join();

This will replace self.child_thread with None, returning an owned Option<JoinHandle<()>> that you can then unwrap and join


Alternatively, to not panic on None:

let status = self.child_thread.take().map(|x| x.join());

Thanks. Code working now. Did not know about take, and was fussing around with various ref approaches.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.