2
votes

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?

1

1 Answers

4
votes

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.