0

When I define a enum like this:

enum MyEnum {
    one,
    two,
    three,
}

and match like this:

let n = MyEnum::two;
match n {
    one => println!("one"),
    two => println!("one"),
    three => println!("three"),
}

it will always print one. The correct way to match would be like this:

let n = MyEnum::two;
match n {
    MyEnum::one => println!("one"),
    MyEnum::two => println!("one"),
    MyEnum::three => println!("three"),
}

Why the compiler does not show an error if I'm clearly matching my enum incorrectly?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Augusto
  • 1,234
  • 1
  • 16
  • 35
  • 2
    You do get a warning: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1effcd846ba29bb3bc5abe89d4204908 . It's easier to see once you address the warnings about naming: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b8f7f5a4053b159695d22f3dac179de2 – Justin Jun 26 '19 at 19:35
  • Specifically: *warning[E0170]: pattern binding `one` is named the same as one of the variants of the type `MyEnum`* .... *help: to match on the variant, qualify the path: `MyEnum::one`* – Shepmaster Jun 26 '19 at 19:39
  • I know it shows a warning, my question is why it compiles? – Augusto Jun 26 '19 at 19:48
  • It looks like your question might be answered by the answers of [Confusing unreachable pattern error](https://stackoverflow.com/q/23810091/155423); [Why is this match pattern unreachable when using non-literal patterns?](https://stackoverflow.com/q/28225958/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 26 '19 at 19:53
  • It is indeed answered in that question @Shepmaster. Thank you – Augusto Jun 26 '19 at 20:04

0 Answers0