【问题标题】:Using vec in a struct在结构中使用 vec
【发布时间】:2019-03-31 10:07:02
【问题描述】:

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

【问题讨论】:

  • 编译器在错误信息中告诉了你原因,建议阅读。如果您不理解错误消息,请提供完整示例以重现错误,并在问题中包含错误消息。
  • 请提供minimal reproducible exampletag description 中有更多 Rust 特定的信息。

标签: rust borrow-checker


【解决方案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

由于@987654321@&lt;T&gt; 让您能够让多个对象指向相同的数据,它只会让您获得对其内容的不可变引用,否则借用检查器将无法保证它不会'当它在其他地方借用时,不能在代码中的某处更改。

解决此问题的方法通常是使用Rc&lt;@987654322@&lt;T&gt;&gt;,它是一种容器类型,允许您通过不可变引用获取对数据的可变引用,并在运行时进行借用检查编译时间:

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 的更多信息

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2022-06-11
    • 2020-02-29
    • 2019-11-10
    相关资源
    最近更新 更多