Need advice on while let
⚓ Rust 📅 2026-01-21 👤 surdeus 👁️ 2Hi!
Rust newbie here! Can you help me understand what is wrong with the following code? It is a contrived example that I think is the MRE of the problem that I am having in my actual code.
enum LinkedList {
Sentinel,
Nonempty {
remaining: Box<LinkedList>,
value: i32,
},
}
impl LinkedList {
fn f(&mut self) {
let mut current = self;
let mut count = 1;
while let LinkedList::Nonempty { remaining, .. } = current {
if count > 1 {
break;
}
current = remaining;
count += 1;
}
*current = LinkedList::Sentinel;
}
}
Trying to run this block yields:
error[E0506]: cannot assign to `*current` because it is borrowed
--> src/main.rs:20:9
|
13 | while let LinkedList::Nonempty { remaining, .. } = current {
| --------- `*current` is borrowed here
...
20 | *current = LinkedList::Sentinel;
| ^^^^^^^^
| |
| `*current` is assigned to here but it was already borrowed
| borrow later used here
The error message was confusing to me: *current is borrowed but that borrow shouldn't extend beyond while let.
If I remove the if block within the while let statement, it runs just fine. So it seems like the break statement is causing the problem but it is not clear to me how.
Thanks!
3 posts - 3 participants
🏷️ Rust_feed