Random text matches any enum value?

I thought it would be an error, but the compiler says it matches anything:

enum Test {
    Item1,
    Item2,
}

fn main() {
    let val = Test::Item2;
    match val {
        Blah => { println!("First"); } // Compiler says Blah matches anything
        Item2 => { println!("Second"); } // Unreachable due to Blah matches anything
    }
}

That's because that's a binding pattern, that is a pattern that matches any value and gives the given "name" to that value. If you want to match an enum value you need to use the pattern Test::Item2.

1 Like

It's very likely that you noticed this while using Item1 instead of Blah. In that case, the first two error messages are:

warning[E0170]: pattern binding `Item1` is named the same as one of the variants of the type `Test`
 --> src/main.rs:9:9
  |
9 |         Item1 => { println!("First"); }
  |         ^^^^^ help: to match on the variant, qualify the path: `Test::Item1`
  |
  = note: `#[warn(bindings_with_variant_name)]` on by default

warning[E0170]: pattern binding `Item2` is named the same as one of the variants of the type `Test`
  --> src/main.rs:10:9
   |
10 |         Item2 => { println!("Second"); }
   |         ^^^^^ help: to match on the variant, qualify the path: `Test::Item2`

Note that the underline tells you "to match on the variant, qualify the path: Test::Item2".

Blah in your case is no different than a pattern with a single binding called Blah. Those are usually useful as the pattern in the last match arm to act as a fall-through (although in some cases people use _ to ignore the binding instead).

What would have helped you in the output to better understand what was happening?

3 Likes