I am learning rust and there is something I don't understand - I can imagine this is a common beginners failure, still I couldn't find an explanation to this specific issue but if it has been asked before I beg your pardon for my annoyance.
The issue comes with the following scenario: I have a struct containing an instance of a dyn trait that I would like to move to a thread. I do not want to share anything between threads but I would like to move the dyn trait instance to the thread, so that the thread owns the instance. This does not work, I get told that dyn Trait + 'static cannot be sent - but I don't understand why.
The scenario corresponds to the following example:
trait Trait {}
struct Struct {}
impl Trait for Struct {}
struct Contains {
t: Box<dyn Trait>,
}
impl Contains {
pub fn run (mut self) {}
}
fn main () {
let c = Contains {
t: Box::new (Struct {}),
};
let runner = std::thread::spawn (move || c.run ());
runner.join ().unwrap ();
}
As I would assume the instance of c is moved to the thread and there is no sharing of it. This can be worked around if I put the instantiation into the closure but this can have other implications if for instance the instantiation of the struct involves cloning of other resources.
Furthermore this only happens if this involves a dyn trait, it works fine if there are only sized objects involved. Why?