Search code examples
rustwhile-loopinfinite-loop

Why is this "while let" loop an infinite loop?


#[test]
fn test_looping() {
    let index: usize = 2;
    while let Some(index) = index.checked_sub(1) {
        println!("{}", index);
    }
}

Why does this create an infinite loop? I'd expect index to be overwritten by the while let expression. Instead, I have to add a couple extra lines to get it to mutate index.


Solution

  • let declares a new binding, shadowing the previous one. It doesn't modify the existing variable. That index isn't initially declared as let mut index is a sign that it's not being mutated.

    To fix it, write:

    #[test]
    fn test_looping() {
        let mut index: usize = 2;
        while let Some(i) = index.checked_sub(1) {
            index = i;
            println!("{}", index);
        }
    }