Basically I have three structs:
- the first encapsulates the other two ("CStruct")
- the second creates/owns an instance of an object ("AStruct")
- the third requires a reference to the object of the second struct to create objects for itself ("BStruct")
The actual code is somewhat extensive, so I've taken only the essential parts and simplified the names to reproduce the issue:
enum Instance {
Something,
SomethingElse
}
struct AStruct {
inst: Instance
}
struct BStruct<'a> {
r_inst: &'a Instance
}
struct CStruct<'a> {
astruct: AStruct,
bstruct: BStruct<'a>
}
fn create_astruct() -> AStruct {
AStruct{inst: Instance::SomethingElse}
}
fn create_bstruct<'a>(astruct: &'a AStruct) -> BStruct<'a> {
BStruct{r_inst: &astruct.inst}
}
fn create_cstruct<'a>() -> CStruct<'a> {
let astruct = create_astruct();
let bstruct = create_bstruct(&astruct);
CStruct{astruct, bstruct}
}
fn main() {
let _cstruct = create_cstruct();
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing local variable `astruct`
--> src/main.rs:30:5
|
29 | let bstruct = create_bstruct(&astruct);
| -------- `astruct` is borrowed here
30 | CStruct{astruct, bstruct}
| ^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `astruct` because it is borrowed
--> src/main.rs:30:13
|
27 | fn create_cstruct<'a>() -> CStruct<'a> {
| -- lifetime `'a` defined here
28 | let astruct = create_astruct();
29 | let bstruct = create_bstruct(&astruct);
| -------- borrow of `astruct` occurs here
30 | CStruct{astruct, bstruct}
| --------^^^^^^^----------
| | |
| | move out of `astruct` occurs here
| returning this value requires that `astruct` is borrowed for `'a`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0505, E0515.
For more information about an error, try `rustc --explain E0505`.
error: could not compile `playground`
To learn more, run the command again with --verbose.
I would have expected this to work since both structs end up being moved in the first and thus should have the same lifetime, unfortunately it seems the borrow checker doesn't agree with me.
So any hints on how to resolve this would be appreciated, preferably without having to change the relations/structure of the structs.