2

I would expect the Rust compiler to complain about the missing cases in match as well as the unknown identifier:

pub enum MyEnum {
    Case1,
    Case2,
}

impl MyEnum {
    fn my_func(&self) {
        match self {
            _whatever_string => println!("Why am I printed ?"),
        }
    }
}

fn main() {
    let x = MyEnum::Case1;
    x.my_func();
}

Why does it compile and call the println?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
bm842
  • 369
  • 2
  • 10

1 Answers1

4

Your example is a special case of something explained here:

let x = 5;

let number = match x {
    1 => "one",
    2 => "two",
    3 => "three",
    4 => "four",
    5 => "five",
    _ => "something else",
};

Consider the last case (_), which matches anything not mentioned before. The compiler does not complain about missing cases (since "everything else" is covered by the last branch).

Your example is essentially the same: A match with one single arm that covers everything. You could also have written _ instead of _whatever_string, or another identifier - that could then be used in the corresponding arm.

So, this match just matches and executes the statements in its single arm. The compiler sees that the single branch covers everything and does not need to complain.

phimuemue
  • 34,669
  • 9
  • 84
  • 115
  • Thanks for your answer. I thought only '_' was accepted as the default arm but it seems not. I can even add more "whatever_identifier" cases without the compiler to complain (except warnings). – bm842 Nov 24 '18 at 05:52
  • 4
    Any implicitly typed, unconstrained identifier can match any value. – Nicola Musatti Nov 24 '18 at 08:01