Beginner Help: Why does an if statement make the compiler reject code that was otherwise valid?

โš“ Rust    ๐Ÿ“… 2025-11-18    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 2      

surdeus

Take 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;
        }
    }
}

image

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

Read full topic

๐Ÿท๏ธ Rust_feed