我使用什么生命周期来创建循环引用彼此的Rust结构?

nx7onnlm  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(86)

我想让结构成员知道他们的父。这大概就是我想做的

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

这是有道理的,但我不知道从这里去哪里。

kq0g1dla

kq0g1dla1#

不可能用借用的指针创建循环结构。
目前还没有任何好的方法来实现循环数据结构;唯一的真实的解决方案是:
1.对Rc<T>使用引用计数,循环结构为Rc::new()Rc:downgrade()。阅读rc module documentation,注意不要创建使用强引用的循环结构,因为这会导致内存泄漏。
1.使用原始/不安全指针(*T)。

相关问题