Oliver Jumpertz

Simplify Match Statements

Category: Rust

Share this snippet to:

// You can use an if-let statement to only handle one specific case
if let Some(value) = some_function_returning_an_option() {
}
// instead of using a match statement only handling one case
match some_function_returning_an_option() {
Some(value) => {
// ...
},
// this is needed because match is exhaustive. It forces you to handle
// all possible cases, although you might not want to
_ => {},
};

Explanation

An if-let statement is a good alternative to a match statement if (and only if) you don’t plan on handling all possible cases of an expression. Match statements are exhaustive, which means that they force you to handle all possivle cases, even if there might be no need for that at all (business-logic wise).

If you stumble upon such a case, it’s way easier to just use an if-let statement because it allows you to handle exactly the case you want to handle. You should, however, not chain if-let statements exhaustive or excessively use their else case. In such a case, a match statement is usually way more readable.

So, if you fall back to code like this:

if let Some(value) = some_function_returning_an_option() {
} else {
}

you can directly fall back to a match statement like this:

match some_function_returning_an_option() {
Some(value) => {
//...
},
None => {
// ...
},
};

Share this snippet to: