在结构中使用 vec

Using vec in a struct

我有一个包含类似结构的 vec 的结构:

struct ProcessNode {
    ...
    children: Vec<Rc<ProcessNode>>,
}

不幸的是,当我尝试将某些内容附加到 vec 中时,我 运行 遇到了一个问题:

let mut parent_node: &mut Rc<ProcessNode> = ...
let mut parent_children: &mut Vec<Rc<ProcessNode>> = &mut parent_node.children;

现在 parent_node 在编译期间检出,但是 parent_children 不能那样引用。为什么?我如何追加到结构中的 vec 字段?

我假设这是您收到的错误消息?

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/main.rs:11:58
   |
11 |     let mut parent_children: &mut Vec<Rc<ProcessNode>> = &mut parent_node.children;
   |                                                          ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

由于 <a href="https://doc.rust-lang.org/std/rc/struct.Rc.html" rel="nofollow noreferrer">Rc</a><T> 使您能够让多个对象指向相同的数据,它只会让您获得对其的不可变引用内容,否则借用检查器将无法保证它不会在代码中的某个地方被更改,而它被借用到其他地方。

解决这个问题的方法通常是使用 Rc<<a href="https://doc.rust-lang.org/std/cell/struct.RefCell.html" rel="nofollow noreferrer">RefCell</a><T>>,这是一种容器类型,允许您获取对具有不可变引用的数据,并在运行时而不是编译时进行借用检查

let parent_node: &Rc<RefCell<ProcessNode>> = ...;

// get a mutable reference to the ProcessNode
// (this is really a RefMut<ProcessNode> wrapper, and this needs to be in scope for as
// long as the reference is borrowed)
let mut parent_node_mut: RefMut<'_, ProcessNode> = parent_node.borrow_mut();

// get mutable reference to children
let parent_children: &mut Vec<_> = &mut parent_node_mut.children;

Playground example

您可以在文档 here

中阅读有关将 RefCellRc 结合使用的更多信息