Match with identical branches, why?

Any reason why this is not compilation time error

    let a = 1;
    match a {
        1 => {}
        1 => {}
        _ => {}
        _ => {}
    }

?

while this is obviously nonsense, but things like these are possible:

    let a = 1;
    let x = 2;
    match a {
        x => {}
        _ => {}
    }

In fact we have here two _ branches, but for language newcomer, this is not obvious, so any reasons to not emit compile time error, for such constructions?

2 Likes

You do get an instance of #[warn(unreachable_patterns)] from all of these overlaps.

1 Like

But why this is warning, not error?

For example for code in this question: rust - Why does match not work while PartialEq/Eq works fine? - Stack Overflow, at first I got two warnings, one for unused vairable (match variable from => println!("1"),), which was not understandable for me, and then warning about unreachable pattern, which also not clear. Only after I understand that x => code, is actually _ => code, not if var == x I undertand compiler warnings.

You can do #![deny(unreachable_patterns)] or even #![deny(warnings)] if you prefer a strict compiler.

@kornel

If I do this in lib.rs or in main.rs it is spread on all crate? What about [[bin]] sections inside library crate, does it cover them also?

Yes.

No, each [[bin]] is effectively its own crate, making its own such choices.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.