I've been trying to port some more c++ code to rust and I ran into the following issue: Playground link.
error[E0597]: `*app` does not live long enough --> src/main.rs:38:18 | 38 | let device = app.create_device(); | ^^^ borrowed value does not live long enough ... 42 | device, | ------ cast requires that `*app` is borrowed for `'static` ... 45 | } | - `*app` dropped here while still borrowed error[E0505]: cannot move out of `app` because it is borrowed --> src/main.rs:41:9 | 38 | let device = app.create_device(); | --- borrow of `*app` occurs here ... 41 | app, | ^^^ move out of `app` occurs here 42 | device, | ------ cast requires that `*app` is borrowed for `'static`
The gist of what is happening is that I have something that implements the
App trait which then allows the user to create an implementation of the
Device trait which is valid for that
App implementation. Both of those are then placed in the
Instance type and used throughout the program.
The main issues I'm trying to solve is that I'd like to provide clues to the compiler that
Box<dyn Device> should not live longer than
Box<dyn App>. I would like to catch the problem where in
Instance, if I don't declare the fields in the correct order,
Box<dyn App gets dropped before
I have also tried explicitly add the lifetime parameter to the trait (Playground link) but I end up with the same error.
Shouldn't this not be an issue since both
dyn App and
dyn Device are allocated on the heap and moving them should be fine?
If I remove the
+ '_ from the
Box<dyn Device> return type, everything compiles, but there's no way to enforce the drop to happen in the correct order.
Is there any way I can solve this?