Gru*_*rig 21 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);
}
Run Code Online (Sandbox Code Playgroud)
我试图用生命周期来安抚编译器而不完全理解我在做什么.
这是我坚持的错误信息:
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
Run Code Online (Sandbox Code Playgroud)
这有点道理,但我不确定从哪里开始.
Chr*_*gan 15
使用借用指针创建循环结构是不可能的.
目前没有任何实现循环数据结构的好方法; 唯一真正的解决方案是:
Rc<T>用具有环状结构Rc::new和Rc:downgrade.阅读rc模块文档并注意不要创建使用强引用的循环结构,因为这会导致内存泄漏.*T).