The following code (playground)
let max_column = 7;
edge = match current_column {
0 => Edge::Left,
max_column => Edge::Right,
_ => Edge::NotAnEdge
};
results in the following error:
error[E0001]: unreachable pattern
--> <anon>:10:9
|
10 | _ => Edge::NotAnEdge
| ^ this is an unreachable pattern
|
note: this pattern matches any value
--> <anon>:9:9
|
9 | max_column => Edge::Right,
| ^^^^^^^^^^
Replacing the variable max_column
with the literal works fine:
let max_column = 7;
edge = match current_column {
0 => Edge::Left,
7 => Edge::Right,
_ => Edge::NotAnEdge
};
Why is _
unreachable in the first example when it can be reached for any values where current_column != max_column
?
The Rust Programming Language explains how a
match
expression is processed, emphasis mine:In your example,
max_column
is the name of the variable to be bound to, not a constant or an outside variable. When the compiler reachesmax_column
, any remaining values will be assigned to that match arm, making subsequent arms unreachable.In your case, you want a match guard:
Note that, as a first approximation,
a
and_
are the same thing in this case! In both cases, the matched variable will be bound to a name (a
or_
respectively), but any identifier prefixed with_
is special-cased to be used as an unused variable placeholder.bluss clarifies and corrects this approximation: