0

I have two structs, A and B, where:

  • A will store an immutable reference to objects of B.
  • B will store an object of A.

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?

arunanshub
  • 581
  • 5
  • 15
  • https://users.rust-lang.org/t/how-do-i-create-self-referential-structures-with-pin/24982 – Svetlin Zarev Aug 16 '21 at 17:22
  • 2
    Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – kopecs Aug 16 '21 at 17:23

0 Answers0