Search code examples
loopsrustvector

How to check if a value in a Vec is None?


I would like to use the fact that Vec.last() returns a None if there is nothing at that index but that index still exists. The problem is that I can't find a way to compare the result to anything inside of a while or if. I can however compare it if I use match, although that seems less efficient than using a while loop. Is there a way to compare it in an if or a while loop?

This is what I'm trying to do, but the self.particles.last() == None is invalid since you can't compare things to None except None as far as I can tell.

while vec.last() == None {
    num += 1;
}

Solution

  • I would use Option::is_none:

    while vec.last().is_none() {
        ...
    }
    

    But that's boring. We're here to learn. Perhaps there's a convoluted, hard to read option where we can flex our Rust muscles? As it happens, there is! Let's take a look at one of my favorite Rust features, pattern matching.

    What's that? Well, normally you'd write something like this, which loops as long we you get Some items and simultaneously binds the items to a variable:

    while let Some(elem) = vec.last() {
        ...
    }
    

    Some(elem) is a pattern. It turns out that None fills the same syntactical role. It's a pattern, albeit one without a variable:

    while let None = vec.last() {
        ...
    }
    

    I admit let without a variable looks odd, and it looks like it's backwards having the None on the left, but it works.

    (Also, I should point out this will be an infinite loop if you don't modify vec.)