1

I have a struct with an optional self-reference:

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

I want to follow the parent reference until the first child before the root node (The root node has no parent). I tried the following code:

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

But this fails to compile with the following error:

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

How can I get a Pathnode from the Rc? Alternatively, what other data type could I use for head? It's OK if I only get an immutable reference or similar at the end.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Sinthorion
  • 267
  • 2
  • 16
  • This seems similar to [this](https://stackoverflow.com/questions/49377231/when-to-use-rc-vs-box). – squiguy Oct 05 '18 at 17:14

1 Answers1

3

You should use references instead of trying to move values around. This should work:

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

Your code calls unwrap() directly on parent, which consumes the Option. It is not possible to move a field out of a struct.

A nice alternative is to use while let:

let mut head: &Pathnode = &node;
while let Some(ref parent) = head.parent  {
    head = parent;
}
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841