Match if statements

Is there a better way to write something like this:

match something {
    Ok(foo) => {
        if foo > 0 {
            condition1
        } else {
            condition2
        }
    }
    Err(_) {
        condition2
    }
}

Yep, you can use match guards.

match something {
    Ok(foo) if foo > 0 => {
        condition1
    }
    _ => {
        condition2
    }
}
2 Likes

Thanks! I wonder why clippy doesn't suggest this.

It might be a lint that is ignored by default. If the lint is missing, you can suggest it to clippy on their github.

You could also write it like this:

use std::i32::MAX;

match something {
    Ok(0 ..= MAX) => condition1,
    _ => condition2,
}

or something like this:

if something.unwrap_or(-1) > 0 {
    condition1
} else {
    condition2
}

I prefer map_or in this case. For me -1 seems too arbitrary.

if something.map_or(false, |n| n > 0) {
    condition1
} else {
    condition2
}
1 Like