Linked list error

I am halfway implementing my LinkedList implementation in rust but could solve this problem.

  Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:34:37
   |
34 |                         last_node = &(*node).next;
   |                                     ^^^^^^^^^^^^^ types differ in mutability
   |
   = note: expected mutable reference `&mut std::option::Option<std::boxed::Box<Node<T>>>`
                      found reference `&std::option::Option<std::boxed::Box<Node<T>>>`
use std::iter::FromIterator;

pub struct SimpleLinkedList<T>(Option<Box<Node<T>>>);
    

struct Node<T> {
    data: T,
    next: Option<Box<Node<T>>>,
}


impl<T> SimpleLinkedList<T> {
    pub fn new() -> Self {
        SimpleLinkedList(None)
    }

    pub fn len(&self) -> usize {
        unimplemented!()
    }

    pub fn push(&mut self, _element: T) {
    
    
        let mut last_node = &mut self.0; 

        loop {
            match last_node {
                
                Some(mut node) => {
                        last_node = &(*node).next;

                }, 
                None => {
                    let new_node = Box::new(Node{data: _element, next: None});
                    *last_node = Some(new_node);
                    break
                }
                
            }
        }
        
    }

    pub fn pop(&mut self) -> Option<T> {
        unimplemented!()
    }

    pub fn peek(&self) -> Option<&T> {
        unimplemented!()
    }

    pub fn rev(self) -> SimpleLinkedList<T> {
        unimplemented!()
    }
}

You need to take a mutable reference, not an immutable one.

last_node = &mut node.next;

Additionally you should not be using mut in Some(mut node).

Some(node) => {
    last_node = &mut node.next;
}, 
1 Like

Thank you for your prompt reply.