我用什么生命周期创建相互引用的Rust结构?

时间:2013-12-20 07:24:17

标签: struct reference circular-reference rust

我想让结构成员知道他们的父母。这大约是我正在尝试做的事情:

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);
}

我试图用生命周期来安抚编译器而不完全理解我在做什么。

这是我坚持的错误信息:

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

这是有道理的,但我不确定从哪里开始。

2 个答案:

答案 0 :(得分:11)

无法使用借用指针创建循环结构。

目前没有任何良好的方式实现循环数据结构;唯一真正的解决方案是:

  1. 使用带有Rc<T>Rc::new的循环结构的Rc:downgrade引用计数。阅读rc module documentation并注意不要创建使用强引用的循环结构,因为这会导致内存泄漏。
  2. 使用原始/不安全指针(*T)。

答案 1 :(得分:0)

摘自“参考周期可能泄漏内存”段落中的官方documentation

enter image description here

相关问题