在结构中使用vec

问题描述 投票:-1回答:1

我有一个结构,持有类似结构的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字段?

rust borrow-checker
1个回答
1
投票

我假设这是你得到的错误信息?

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

由于Rc使您能够让多个对象指向相同的数据,因此它只允许您获取对其内容的不可变引用,否则借用检查器将无法保证它不会在某处被更改代码在借用其他地方的时候。

解决这个问题的方法通常是使用Rc<RefCell>,它是一种容器类型,允许您使用不可变引用获取对数据的可变引用,并在运行时而不是编译时借用检查:

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

你可以在RefCell文档中阅读更多关于使用Rchere的信息。

© www.soinside.com 2019 - 2024. All rights reserved.