rust - 在结构中使用 vec

标签 rust borrow-checker

我有一个包含类似结构的 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 在编译期间 check out ,但是 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="noreferrer noopener nofollow">Rc</a><T>使您能够让多个对象指向相同的数据,它只允许您获得对其内容的不可变引用,否则借用检查器将无法保证它不会在代码中的某处被更改而它是从别处借来的。

解决这个问题的方法通常是使用 Rc<<a href="https://doc.rust-lang.org/std/cell/struct.RefCell.html" rel="noreferrer noopener nofollow">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

您可以阅读有关使用 RefCell 的更多信息与 Rc在文档中 here

关于rust - 在结构中使用 vec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439815/

相关文章:

rust - 我如何安全地使用可变借用的对象?

reference - 为什么我可以返回对本地文字的引用而不是变量?

rust - 在闭包中借用可变引用来对向量进行排序

rust - 如何模式匹配包含 &mut 枚举的元组,并在一个匹配臂中使用枚举并在另一个匹配臂中使用递归调用?

rust - 我可以创建一个指向堆栈对象的拥有指针吗

rust - crypto::hmac::Hmac::new 中的参数类型不匹配

string - 如何加速 UTF-8 字符串处理

Rust Playground - 提供命令行参数

python - PyO3 将 rust 结构转换为 &PyAny

Rust 零复制生命周期处理