0

I have two structs, Parent and Child.

The Child references Parent's data, so I used a lifetime, but I got the error cannot borrow `p.childs` as immutable because it is also borrowed as mutable.

struct Parent<'a> {
    data: String,
    childs: Vec<Child<'a>>,
}

struct Child<'a> {
    parent_data: &'a String,
}

impl<'a> Parent<'a> {
    fn parse(&'a mut self) {
        for _i in 0..10 {
            let c = Child {
                parent_data: &self.data,
            };
            self.childs.push(c);
        }
    }
}

fn main() {
    let mut p = Parent {
        data: "Hello".to_string(),
        childs: Vec::new(),
    };

    p.parse();

    for i in p.childs.iter() {
        println!("{:?}", i.parent_data);
    }
}

Errors:

error[E0502]: cannot borrow `p.childs` as immutable because it is also borrowed as mutable
  --> src/main.rs:29:14
   |
27 |     p.parse();
   |     - mutable borrow occurs here
28 | 
29 |     for i in p.childs.iter() {
   |              ^^^^^^^^
   |              |
   |              immutable borrow occurs here
   |              mutable borrow later used here

How should I change the code?

trent
  • 25,033
  • 7
  • 51
  • 90
  • Welcome to Stack Overflow! It helps if you read the whole error. The error message starts with the line `error[E0502]:` and if you search for that you find a lot of hits that will help you understand the problem. – trent Jan 09 '20 at 02:14
  • 1
    see also https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct – Stargateur Jan 09 '20 at 02:47

0 Answers0