Why does this fail to compile?
I'm trying to get a reference to the tail of a linked list, and here's the code I wrote:
pub struct ListNode {
pub next: Option<Box<ListNode>>,
}
fn tail(mut head: &mut Option<Box<ListNode>>) -> &mut Option<Box<ListNode>> {
while let Some(x) = head.as_mut() {
head = &mut x.next;
}
head
}
This fails to compile because it thinks I'm borrowing head as mutable twice. I was able to get to compile by changing it to this:
fn tail(mut head: &mut Option<Box<ListNode>>) -> &mut Option<Box<ListNode>> {
while head.is_some() {
head = &mut head.as_mut().unwrap().next;
}
head
}
It appears to me that these two functions do the exact same thing, but the first one looks a lot cleaner. Why doesn't it compile? Is there a better way of doing this than what I changed it to?
from Recent Questions - Stack Overflow https://ift.tt/3qSCGoQ
https://ift.tt/eA8V8J
Comments
Post a Comment