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?