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);
}