I have two structs, A
and B
, where:
A
will store an immutable reference to objects ofB
.B
will store an object ofA
.
My goal is to insert a reference to the newly created object of B
into A::vec_of_b
before returning. Here is my attempt at executing above goal:
struct A<'a> {
vec_of_b: Vec<&'a B<'a>>
}
impl<'a> A<'a> {
pub fn new() -> Self {
Self { vec_of_b: Default::default() }
}
}
struct B<'a> {
a_struct: A<'a>,
}
impl<'a> B<'a> {
pub fn new(data: A<'a>) -> Self {
let mut bvar = Self { a_struct: data };
// I want to insert a reference to the newly created object `bvar`
bvar.a_struct.vec_of_b.push(&bvar); // <-- this line throws error
bvar
}
}
pub fn main() {
let a = A::new();
let mut b = B::new(a);
}
But I received an error related to lifetimes:
error[E0502]: cannot borrow `bvar.a_struct.vec_of_b` as mutable because it is also borrowed as immutable
error[E0515]: cannot return value referencing local variable `bvar`
error[E0505]: cannot move out of `bvar` because it is borrowed
How to solve this problem?