How can I find the wanted node in loop and change it after

I want to implement a LinkedList . In append() method, I want to find the last node and change its next property. I have tried to resolve the problem but failed.
The error is

error[E0506]: cannot assign to `node.next` because it is borrowed
  --> src/linked_list.rs:35:9
   |
28 |             let next = &mut node.next;
   |                        -------------- borrow of `node.next` occurs here
...
35 |         node.next = Some(Box::new(new_node));
   |         ^^^^^^^^^
   |         |
   |         assignment to borrowed `node.next` occurs here
   |         borrow later used here

And the code is following:

struct Node {
    value: u32,
    next: Option<Box<Node>>,
}
impl Node {
    fn new(val: u32) -> Self {
        return Node {
            value: val,
            next: None,
        };
    }
}

struct LinkedList {
    len: u32,
    head: Box<Node>,
}
impl LinkedList {
    fn new() -> Self {
        LinkedList {
            head: Box::new(Node::new(0)),
            len: 0,
        }
    }
    fn append(&mut self, new_node: Node) {
        let mut node = &mut self.head;
        loop {
            let next = &mut node.next;
            if let Some(real_next) = next {
                node = real_next;
            } else {
                break;
            };
        }
        node.next = Some(Box::new(new_node));
        self.len += 1;
    }
}
fn main() {}

Linked lists and the Borrow Checker don't always play nice. Here is a link to a thread about a tutorial going over all the pitfalls and subtleties of linked lists in Rust.

This should work:

struct Node {
    value: u32,
    next: Option<Box<Node>>,
}
impl Node {
    fn new(val: u32) -> Self {
        return Node {
            value: val,
            next: None,
        };
    }
}

struct LinkedList {
    len: u32,
    head: Box<Node>,
}
impl LinkedList {
    fn new() -> Self {
        LinkedList {
            head: Box::new(Node::new(0)),
            len: 0,
        }
    }
    fn append(&mut self, new_node: Node) {
        let mut node = &mut self.head;
        
        while node.next.is_some() {
            node = node.next.as_mut().unwrap();
        }
        
        node.next = Some(Box::new(new_node));
        self.len += 1;
    }
}
fn main() {}

Playground.

1 Like

Thank you very much! I will learn this thread.

Thank you very much! It's awesome and easy. I have try to use Rc or RefCell but failed. I will learn it more deeply.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.