I am learning about link list & thought to write a simple one.
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
with a impl
block
impl ListNode {
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
// Issue with insert method.
fn insert(&mut self, val: i32) -> &mut Self {
// Match causing issue because it takes mut ref.
match &mut self.next {
Some(node) => node.insert(val),
None => {
// Cannot update value because only one mut ref allowed.
self.next = Some(Box::new(ListNode::new(val)));
self
}
}
}
}
If I replace mut
ref with just self in insert() it works fine but at every insert call transferring ownership doesn't feel logical. Is there any way to insert new item in link list while only taking node's ref?