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

标签 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

这有一定道理,但我完全不确定从这里到哪里去。

最佳答案

不可能用借用的指针创建循环结构。

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

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

关于struct - 我使用什么生命周期来创建循环引用彼此的 Rust 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39321563/

相关文章:

c++ - 将结构体成员声明为 uint32_t 时的额外字节

Ruby 变量引用其他变量

c# - 三层架构 C# 中的循环引用问题

mysql - 数据库设计 : Circular reference and how to correct it

c++ - 如何避免某些值的简单组的长构造函数?

c - 循环遍历文件并读取所有记录

c++ - 将函数的返回值存储在引用 C++ 中

iphone - 具有自动引用计数的 iOS 项目中的 RestKit

python-3.x - 如何创建元组的循环引用?

c - 为什么我的 C 程序不能正常工作?