Search code examples
rustoption-type

unwrap or evalulate to false in rust


I have encountered several cases similar this:

if let Some(x) = formula_chars.peek() {
    if x.is_lowercase() {
        todo!()
    }
}

where I would like an expression to evaluate to false if an Option is None or some operation on the Some variant, (in this case is_lowercase() ) returns false. However, the only way I've found to do this is using nested if statements as shown above. Is there some way to do this with a single expression? preferably something along the lines of the code below:

note: code below doesn't work it is just to illustrate the desired behavior

if formula_chars.peek().unwrap_or(false).is_lowercase() {
    todo!()
}

P.S. in this specific case I know I could just unwrap_or to a non-lowercase character e.g.

if formula_chars.peek().unwrap_or('_').is_lowercase() {
    todo!()
}

but I'm looking for a more general (and preferably less bodge-y) solution


Solution

  • You can use Option::is_some_and:

    if formula_chars.peek().is_some_and(|x| x.is_lowercase()) {
        todo!()
    }
    

    Instead of defining a lambda that immediately delegates to another function, I find it slightly more ergonomic to pass the delegated function as a path expression:

    if formula_chars.peek().is_some_and(char::is_lowercase) {
        todo!()
    }
    

    However, the method call expression used in the lambda performs auto-deref on the receiver x (if necessary) but this doesn't happen if the function is passed as a path expression. Therefore, since in this case char::is_lowercase takes a char not &char, if you have an Option<&char> you could first call Option::copied:

    if formula_chars.peek().copied().is_some_and(char::is_lowercase) {
        todo!()
    }
    

    It's just personal taste. YMMV.