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

前端 未结 2 1310
夕颜
夕颜 2020-11-28 14:02

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

        
相关标签:
2条回答
  • 2020-11-28 14:45

    From the official documentation in "Reference Cycles Can Leak Memory" paragraph:

    0 讨论(0)
  • 2020-11-28 15:00

    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).
    0 讨论(0)
提交回复
热议问题