Rust Programming: Matches Are Exhaustive

0
Matches Are Exhaustive is a feature of Rust that ensures that all possible cases are handled in a match expression. This is done by requiring that all arms of the match expression cover all possible values of the input. If a case is not covered, Rust will not compile the code. For example, the following code will not compile because it does not handle the None case of the Option<i32>:

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        Some(i) => Some(i + 1),
    }
}

Rust will give the following error:

error[E0004]: non-exhaustive patterns: `None` not covered

To fix this error, we need to add an arm to the match expression that handles the None case. For example, we could add the following arm:

match x {
    Some(i) => Some(i + 1),
    None => None,
}

This code will now compile, and it will correctly handle both the Some and None cases of the Option<i32>.

Post a Comment

0Comments
Post a Comment (0)