【问题标题】:How do I recursively follow a self-referential Rc? [duplicate]如何递归地遵循自引用 Rc? [复制]
【发布时间】:2018-10-05 16:09:43
【问题描述】:

我有一个带有可选自引用的结构:

struct Pathnode {
    pos: Pos,
    parent: Option<Rc<Pathnode>>,
}

我想跟随parent 引用直到根节点之前的第一个子节点(根节点没有父节点)。我尝试了以下代码:

let mut head: Pathnode = node;
while head.parent.is_some() {
    head = *head.parent.unwrap();
}

但是编译失败,出现以下错误:

error[E0507]: cannot move out of borrowed content
   --> file.rs on line 134:24
    |
139 |                 head = *head.parent.unwrap();
    |                        ^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content

如何从Rc 获得Pathnode?或者,我可以为head 使用什么其他数据类型?如果我最后只得到一个不可变的引用或类似的引用就可以了。

【问题讨论】:

  • 这似乎类似于this

标签: rust


【解决方案1】:

您应该使用引用而不是尝试移动值。这应该有效:

let mut head: &Pathnode = &node;
while head.parent.is_some() {
    head = head.parent.as_ref().unwrap();
}

您的代码直接在parent 上调用unwrap(),这会消耗Option。无法将字段移出结构。

一个不错的选择是使用while let:

let mut head: &Pathnode = &node;
while let Some(ref parent) = head.parent  {
    head = parent;
}

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2022-08-20
    • 2010-11-02
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多