admin管理员组

文章数量:1389768

I am learning Rust programming language and having problems with the borrow checker while implementing some basic data structure (Linked List).

I have defined a List structure this way:

#[derive(Debug)]
pub struct Node {
    value: i8,
    next: Option<Box<Node>>
}

The code for addition new nodes is:

    fn append(&mut self, value: i8)  {
        let mut leaf = self;
        loop {
            match leaf.next {
                None => break,
                Some(ref mut next) => {
                    leaf = next
                }
                
            }
        }
        // let mut leaf: &Node = self.find_leaf();
        let new_node: Node = Node {
            value: value, 
            next: None
        };
        leaf.next = Some(Box::new(new_node)); 
    }

(So it traverses the list and insert a new Node at the end of it).

Now I am trying to delete a Node by value. So the idea is that I am building a delete function that takes a given node (head). Finds a node it needs to delete, and finally should update the references, so it's possible to "skip" the needed node.

The implementation looks like this:

fn delete(&mut self, value: i8){
        let mut current = self;
        loop {
            println!("{}", current.value);

            match current.next {
                None => break,
                Some(ref mut next_node) =>
                    {
                        if next_node.value == value {
                            println!("Need to drop: > {} <", next_node.value);
                            println!("Next node is:  > {:?} <", next_node.next);
                            match next_node.next.take() {
                                None =>  
                                    {
                                        println!("Nothing under next");
                                        current = next_node;
                                    }
                                    
                                Some(next_node_next) => 
                                    {
                                        println!("Doing jump to next_next");
                                        current.next = Some(next_node_next)
                                    }
                                    
                            } 

                           
                        } else {
                            current = next_node
                        }
                    }
            }
        }
    }

However I am getting the following error:

lue == value {
delete
cannot assign to `current.next` because it is borrowed
`current.next` is assigned to here but it was already borrowed

The full code is here: /?version=stable&mode=debug&edition=2024&gist=5e41ffc0c53eccde7e8d7b74391b7716

本文标签: rustRemoving element from linked listStack Overflow