Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this match pattern unreachable when using non-literal patterns?

Tags:

rust

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 warning:

warning: unreachable pattern
  --> src/main.rs:10:9
   |
9  |         max_column => Edge::Right,
   |         ---------- matches any value
10 |         _ => Edge::NotAnEdge
   |         ^ unreachable pattern
   |
   = note: #[warn(unreachable_patterns)] on by default

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?

like image 570
Mike Vella Avatar asked Jan 29 '15 22:01

Mike Vella


Video Answer


1 Answers

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 to make max_column a real constant:

let current_column = 1;
const MAX_COLUMN: i32 = 7;
edge = match current_column {
    0          => Edge::Left,
    MAX_COLUMN => Edge::Right,
    _          => Edge::NotAnEdge
};

Or if that's not possible, 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.)

like image 112
Shepmaster Avatar answered Oct 12 '22 17:10

Shepmaster