Why did `match` compile with unknown symbols?

In my recent stream I wrote a match the looked something like this:

    match sq {
        Empty => {
        },
        Suicide => { 
            bs.dead = true;
        },
        ObstacleHard => {
            print_errln!("On Obstable");
        },
        ObstacleSoft => {
            town.set( bs.pos, cell_type::Empty );
            bs.version += 1;
        },

All the options are missing the enum type, they should have been cell_type::Empty, etc. Yet it compiled nonetheless. It didn't work, it just always picked the Empty option (I put a print there to see that).

Why did this compile, and what was it actually doing?

This is because the match treated each of those identifiers as variable names. It's easier to see what's it's doing in an example like this:

match my_number {
    0 => println!("zero"),
    1 => println!("one"),
    x => println!("something else: {}", x)
}

The value of my_number is bound to the variable x for the last match clause.

Note that in your case, you should have seen several "warning: unreachable pattern" messages (because the first match clause would always match, making the other 3 unreachable). That is unfortunately your only hint that something went wrong.

2 Likes

Thank you, that would explain why it compiles.

A chatter also indicated I should have seen warning messages. I just went back now to confirm. It appears to be a problem with the CodinGame site, when it compiles successfully it doesn't show the compiler output. Thus without any other errors I don't even see those warnings. :frowning:

Though even with errors (I added now), those warnings don't come up. I guess my introduced errors just trigger earlier in the compilation phase.

1 Like

You could also try the #[deny(unreachable_patterns)] option, which would have caused your code to fail to build. Maybe then you would have seen the error. Here is an example: playground link

1 Like

#![deny(warnings)] converts all warnings into errors, so maybe that will make CodinGame site display them.

4 Likes