Beginner Help: Why does an if statement make the compiler reject code that was otherwise valid?
โ Rust ๐ 2025-11-18 ๐ค surdeus ๐๏ธ 2Take the following code as an example.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
// This one is fine
fn test1(mut node: &mut Box<ListNode>) {
while let Some(next) = &mut node.next {
node = next;
}
}
// This one won't compile!
fn test2(mut node: &mut Box<ListNode>) {
while let Some(next) = &mut node.next {
if true {
node = next;
}
}
}
The compiler thinks test1 is fine but treats test2 as illegal because it "cannot borrow node.next as mutable more than once at a time". Why does adding an if statement cause such a drastic difference? Why isnโt the same error reason applied to test1? In my view, test1 is already illegal because next and node are both mutable reference to the same object.
4 posts - 3 participants
๐ท๏ธ Rust_feed
