I have two objects where the second one requires the fist one to outlive it because it holds a reference to the first one. I need to move both of them into a thread, but the compiler is complaining that the first one doesn't live long enough. Here is the code:
use std::thread;
trait Facade: Sync {
fn add(&self) -> u32;
}
struct RoutingNode<'a> {
facade: &'a (Facade + 'a),
}
impl<'a> RoutingNode<'a> {
fn new(facade: &'a Facade) -> RoutingNode<'a> {
RoutingNode { facade: facade }
}
}
fn main() {
struct MyFacade;
impl Facade for MyFacade {
fn add(&self) -> u32 {
999u32
}
}
let facade = MyFacade;
let routing = RoutingNode::new(&facade);
let t = thread::spawn(move || {
let f = facade;
let r = routing;
});
t.join();
}
And the error:
error: `facade` does not live long enough
--> <anon>:27:37
|
27 | let routing = RoutingNode::new(&facade);
| ^^^^^^ does not live long enough
...
35 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I believe I understand what the error is telling me: that once the facade
object is moved to the thread, the reference will no longer be valid. But I was unable to find a working solution to this problem, assuming I would like to keep the structures intact.