0

Here is my code to implement Linked list:

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

#[derive(Debug)]
pub struct LinkedList<'a, T> {
    head: Option<Box<Node<T>>>,
    tail: Option<&'a mut Box<Node<T>>>,
    len: usize,
}

impl<'a, T> LinkedList<'a, T> where T: Clone {
    pub fn new() -> Self {
        LinkedList { head: None, tail: None, len: 0 }
    }

    pub fn append(&'a mut self, value: T) {
        let tail = Node { next: None, value };
        let tail = Some(Box::new(tail));
        if let Some(mut node) = self.tail.take() {
            node.next = tail;
            self.tail = node.next.as_mut();
        } else {
            self.head = tail;
            // if I remove lifetime 'a from this function to fix borrow issue, I get an error like:
            // cannot infer an appropriate lifetime for autoref due to conflicting requirements
            self.tail = self.head.as_mut();
        }
        self.len += 1;
    }
}

I'm getting error inside for loop. When I remove the lifetime 'a from append function to fix the borrow issue, I get an error: "cannot infer an appropriate lifetime for autoref due to conflicting requirements" while borrowing mutable ref of self.head.

fn main() {
    let mut list = LinkedList::<i32>::new();
    let arr = [6,1,8,2,3,5];
    for x in arr {
        // cannot borrow `list` as mutable more than once at a time
        list.append(x);
    }
    println!("List {:?}", list);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • [Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial.github.io/too-many-lists/) – Shepmaster Mar 05 '22 at 19:38
  • 2
    You're going to run into [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/q/32300132/155423). Even outside of that, your data structure would allow for getting a mutable reference to the same value twice (once starting at `head` and once starting at `tail`), which is disallowed in safe Rust. – Shepmaster Mar 05 '22 at 19:39

0 Answers0