You already have a value of the correct reference type, so the as_mut
is unnecessary.
while let Some(x) = head {
head = &mut x.next;
}
head
I can't speak to why your first example doesn't compile, as I'm still no expert in speaking "borrow checker" myself, but my guess is that Rust is just being conservative and assuming that the head.as_mut()
borrow lasts into the variable x
, which gets put into head
, and therefore is a mutable borrow lasting as long as head
does, whereas when we directly access it as I do above, Rust is smart enough to understand what's really happening.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…