我使用什么生命周期来创建循环引用彼此的 Rust 结构? [英] What lifetimes do I use to create Rust structs that reference each other cyclically?

查看:57
本文介绍了我使用什么生命周期来创建循环引用彼此的 Rust 结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要结构成员知道他们的父母.这大约是我想要做的:

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.

推荐答案

使用借用指针创建循环结构是不可能的.

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. Rc 中使用引用计数; 带有 Rc::newRc:downgrade.阅读 rc 模块文档 并注意不要创建使用强引用的循环结构,因为这会导致内存泄漏.
  2. 使用原始/不安全的指针 (*T).
  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).

这篇关于我使用什么生命周期来创建循环引用彼此的 Rust 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆