我希望结构成员知道他们的父级。这大约是我正在尝试做的事情:
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
这有一定道理,但我完全不确定从这里到哪里去。
最佳答案
不可能用借用的指针创建循环结构。
目前没有任何好的方法来实现循环数据结构;唯一真正的解决方案是:
- 使用引用计数
Rc<T>
具有Rc::new
的循环结构和Rc:downgrade
.阅读rc
module documentation并注意不要创建使用强引用的循环结构,因为这会导致内存泄漏。 - 使用原始/不安全指针 (
*T
)。
关于struct - 我使用什么生命周期来创建循环引用彼此的 Rust 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39321563/