Hi, as a newbie, i need help for trying to write a linked list to find some position to be changed.
pub(crate) struct Node<T>(T, Option<Box<Node<T>>>);
pub(crate) struct LinkedList<T>(Option<Box<Node<T>>>);
pub(crate) struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
pub(crate) struct IterMut<'a, T> {
next: Option<&'a mut Node<T>>,
}
It's not compiled for a mutable find() like this:
pub fn find_mut<'a>(&'a mut self, start: Option<&'a mut Node<T>>, value: &T) -> IterMut<'a, T>
where
T: PartialEq,
{
let mut head = if let Some(_) = start {
start
} else {
self.0.as_deref_mut()
};
loop {
match head {
Some(&mut Node(ref v, ref mut next)) => { // 155
if v == value {
// rr = head;
break;
} else {
head = next.as_deref_mut();
}
}
None => {
// rr = head; // to Tail
break;
}
}
}
IterMut { next: head } // 170 <- error here
}
it shows the error like these:
cannot move out of head
because it is borrowed
move out of head
occurs here r...)
linkedlist.rs(155, 39): borrow of head.0.1
occurs here
linkedlist.rs(143, 21): lifetime 'a
defined here
linkedlist.rs(170, 9): returning this value requires that head.0.1
is borrowed for 'a
But it would be compiled ok for a non-mutable find():
pub fn find<'a>(&'a self, start: Option<&'a Node<T>>, value: &T) -> Iter<T>
where
T: PartialEq,
{
let mut head = if let Some(_) = start {
start
} else {
self.0.as_deref()
};
loop {
match head {
Some(&Node(ref v, ref next)) => {
if v == value {
break;
} else {
head = next.as_deref();
}
}
None => {
break;
}
}
}
Iter { next: head }
}