To put the whole struct in Arc
you'll just need to actually two structs – the inner one and the outer one (although wrapping separate fields would be a better idea, especially if you don't want the thread to acces the whole struct). You can implement start
only on the outer one.
struct MyInner { s: String }
struct My { inner: Arc<MyInner> }
impl My {
fn start(&self) {
let local_self = self.inner.clone();
thread::spawn(move || {
local_self.test();
});
}
}
Note that I've changed &str
to String
, which was a direct cause of the error (you can't share references in non-scoped threads).
Note that if you want the thread to make changes to original fields, you'll need to wrap this field in a Mutex
or some atomic
type.