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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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).
Any implicitly typed, unconstrained identifier can match any value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.