Why is this match pattern unreachable when using n

2019-01-04 03:49发布

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?

标签: rust
1条回答
Rolldiameter
2楼-- · 2019-01-04 04:13

The Rust Programming Language explains how a match expression is processed, emphasis mine:

When the match expression executes, it compares the resulting value against the pattern of each arm, in order.

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 reaches max_column, any remaining values will be assigned to that match arm, making subsequent arms unreachable.

In your case, you want a match guard:

let current_column = 1;
let max_column = 7;
edge = match current_column {
    0                    => Edge::Left,
    a if a == max_column => Edge::Right,
    _                    => Edge::NotAnEdge
};

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:

_ is a separate special case, it's not a variable binding at all, but it is the absence of one! Matching against _x moves the value into _x, _ does no such thing. (The difference is observable.)

查看更多
登录 后发表回答