Search code examples
rustfor-in-loop

Does manually breaking early from a for loop make sense when testing if a linked list contains an item?


While following a basic tutorial, I'm faced with this function:

use std::collections::LinkedList;

// ...

pub fn contains(&self, x: i32, y: i32) -> bool {
    let mut ch = 0;
    let list: &LinkedList<Block> = &self.body;

    for block in list {
        if block.x == x && block.y == y {
            return true;
        }
        ch += 1;
        if ch == list.len() - 1 {
            break;
        }
    }

    return false;
}

It felt obvious that I could get rid of the whole if ch == list.len() - 1 part and write it like so:

pub fn contains(&self, x: i32, y: i32) -> bool {
    for block in &self.body {
        if block.x == x && block.y == y {
            return true;
        }
    }
    return false;
}

It seems to work fine, but maybe there is something that I've missed? Is it just an unnecessary overhead that an author of the tutorial made by mistake?


Solution

  • As written in the original 'tutorial' version, it doesn't seem to look at the last element. Consider a list of length 2 where the second element is the one you're looking for.

    After the first comparison, ch becomes 1. It's now equal to the list length minus 1, so you break out of the loop just before the loop would (if executed one more time) find the last element.

    That doesn't make much sense, so I conclude yours is not only shorter but correct.