1

While learning Rust, I'm implementing a singly linked stack. I have the following structures defined:

type Link<T> = Option<Box<Node<T>>>;

#[derive(Debug)]
struct Node<T> {
    value: T,
    next: Link<T>,
}

I made the following function to push a value at the end of the stack:

impl<T> Node<T> {
    fn push_last(parent: &mut Link<T>, value: T) {
        match *parent {
            None => {
                *parent = Some(Box::new(Node { value: value, next: None }));
            },
            Some(ref mut boxed_node) => {
                Self::push_last(&mut boxed_node.next, value);
            }
        }
    }
}

It works great, so I'm happy with that. What I would like to do now is unroll the recursion into a loop. I tried to do it this way:

fn push_last(mut parent: &mut Link<T>, value: T) {
    loop {
        match *parent {
            None => {
                *parent = Some(Box::new(Node {
                    value: value,
                    next: None,
                }));
                break;
            }
            Some(ref mut boxed_node) => {
                parent = &mut boxed_node.next;
            }
        }
    }
}

This is pretty much the same, except parent is "incremented" in the function. However I get borrowing issues:

error: cannot assign to `*parent` because it is borrowed [--explain E0506]
   --> src/main.rs:15:21
    |>
15  |>                     *parent = Some(Box::new(Node {
    |>                     ^ assignment to borrowed `*parent` occurs here
...
21  |>                 Some(ref mut boxed_node) => {
    |>                      ------------------ borrow of `*parent` occurs here

error: cannot borrow `parent.0` as mutable more than once at a time [--explain E0499]
   --> src/main.rs:21:22
    |>
21  |>                 Some(ref mut boxed_node) => {
    |>                      ^^^^^^^^^^^^^^^^^^
    |>                      |
    |>                      second mutable borrow occurs here
    |>                      first mutable borrow occurs here
...
26  |>     }
    |>     - first borrow ends here

error: cannot assign to `parent` because it is borrowed [--explain E0506]
  --> src/main.rs:22:21
   |>
21 |>                 Some(ref mut boxed_node) => {
   |>                      ------------------ borrow of `parent` occurs here
22 |>                     parent = &mut boxed_node.next;
   |>                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `parent` occurs here

I really do not get why the first function works and not the second one since they are essentially the same.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
AntoineWDG
  • 539
  • 2
  • 11

0 Answers0