What lifetimes do I use to create Rust structs that reference each other cyclically?

本秂侑毒 提交于 2019-11-26 09:51:09

问题


I\'d like to have struct members that know their parent. This is approximately what I\'m trying to do:

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

I tried to appease the compiler with lifetimes without completely understanding what I was doing.

Here\'s the error message I\'m stuck on:

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

That makes some sense, but I\'m not at all sure where to go from here.


回答1:


It is not possible to create cyclic structures with borrowed pointers.

There is not any good way of achieving cyclic data structures at present; the only real solutions are:

  1. Use reference counting with Rc<T> with a cyclic structure with Rc::new and Rc:downgrade. Read the rc module documentation and be careful to not create cyclic structures that use strong references, as these will cause memory leaks.
  2. Use raw/unsafe pointers (*T).


来源:https://stackoverflow.com/questions/20698384/what-lifetimes-do-i-use-to-create-rust-structs-that-reference-each-other-cyclica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!