Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching on C-like enums when values are not imported cause unintuitive behaviour #10402

Closed
LeoTestard opened this issue Nov 10, 2013 · 5 comments

Comments

@LeoTestard
Copy link
Contributor

When doing pattern matching on a C-like enum whose values haven't be imported in the current namespace, like :

mod foo {
    enum Bar {
        Baz,
        Qux
    }
}

// ...

match someBar {
    Baz => // ...
    Qux => // ...
}

Rustc doesn't know Baz and Qux are values, since they are not imported.
The first Baz pattern is thus considered as a binding, and all following patterns are seen as "unreachable".

Maybe we should put the enum value names inside the namespace of the enum type (like C++11 enum classes), and, in any case, implement a better error or warning message. Many people apparently ran into this issue, and found it very weird and hard to debug. (cc @cmr )

@sfackler
Copy link
Member

enum class style enums are proposed in #10090. There's also #10304 which proposes a warning for upper case match variables which would help in this kind of situation.

@huonw
Copy link
Member

huonw commented Nov 10, 2013

This would also be resolved by forcing local variables to be cased_like_this and enum variants LikeThis ala Haskell, but I imagine that might be going a little too far for some people.

@conradkleinespel
Copy link
Contributor

I'm not sure if this is the same issue, but when using a non existent identifier in a pattern match with a enum, all following matches are unreachable.

Here the example code:

enum Greeting {
    Hello,
    ByeBye
}

fn main() {
    let that = Hello;
    match that {
        Hello => (),
        NonExistent => (),
        ByeBye => ()
    }
}

And a pre-populated Rust Playground link:
http://is.gd/acpYw6

@eefriedman
Copy link
Contributor

We now print a message like warning: pattern binding Hellois named the same as one of the variants of the typeGreeting``; that's probably good enough.

@alexcrichton
Copy link
Member

Thanks @eefriedman!

Jarcho pushed a commit to Jarcho/rust that referenced this issue Feb 26, 2023
Rustup

Looks like `@flip1995`  is busy.

r? `@ghost`

changelog: None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants