Jakich okresów używam do tworzenia struktur Rust, które odnoszą się do siebie cyklicznie?
Chciałbym mieć członków struktury, którzy znają swojego rodzica. To jest w przybliżeniu to, co próbuję zrobić:
struct Parent<'me> {
children: Vec<Child<'me>>,
}
struct Child<'me> {
parent: &'me Parent<'me>,
i: i32,
}
fn main() {
let mut p = Parent { children: vec![] };
let c1 = Child { parent: &p, i: 1 };
p.children.push(c1);
}
Próbowałem uspokoić kompilator przez całe życie, nie do końca rozumiejąc, co robię.
Oto komunikat o błędzie, na którym utknąłem:
error[E0502]: cannot borrow `p.children` as mutable because `p` is also borrowed as immutable
--> src/main.rs:13:5
|
12 | let c1 = Child { parent: &p, i: 1 };
| - immutable borrow occurs here
13 | p.children.push(c1);
| ^^^^^^^^^^ mutable borrow occurs here
14 | }
| - immutable borrow ends here
To ma jakiś sens, ale nie jestem pewien, dokąd stąd się udać.