Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing unreachable pattern error

Tags:

rust

I encountered a very confusing error message from the Rust compiler when using the match statement.

enum Name {
    Known,
}

fn unreachable_pattern(n: Name) -> usize {
    use Name::*;

    match n {
        Unknown => 1,
        Known => 1,
    }
}

The Rust compiler complains about an unreachable pattern:

error[E0001]: unreachable pattern
  --> src/main.rs:10:9
   |
10 |         Known => 1,
   |         ^^^^^ this is an unreachable pattern
   |
note: this pattern matches any value
  --> src/main.rs:9:9
   |
9  |         Unknown => 1,
   |         ^^^^^^^

To a human, the real error is that Unknown is missing from the definition of Name, which is easier to spot when you do not have 40 other variants already.

like image 694
Matthieu M. Avatar asked May 22 '14 14:05

Matthieu M.


1 Answers

This is actually a known issue at the moment; it is not a bug proper, but rather a quality of implementation issue.

The issue boils down to irrefutable matches, i.e.:

match variable {
    1 => 2,
    i => 2 * i
}

Here i is an irrefutable match, meaning it always matches, no matter the value of variable.


Well, we have the same issue with that weird report: because Unknown is unknown, it becomes a name for a variable in an irrefutable match! It is unintended, of course, but it makes perfect sense for the compiler.

The good news is that the compiler starts complaining as soon as the next attempted match, so you can easily find out which match is irrefutable.

A style-lint is expected which would help in this issue, it would report Unknown to be an improperly capitalized variable thus underlining that the compiler does not see it as an enum variant.

There are plenty of variations for this bug (see the duplicates), it might also be caused by improperly importing an enum for example and thus not having its variants in scope.

like image 188
Matthieu M. Avatar answered Nov 06 '22 13:11

Matthieu M.