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

Issue with comparison of uint with zero inside case by type #19347

Closed
pavel-odintsov opened this issue Mar 1, 2017 · 4 comments
Closed

Issue with comparison of uint with zero inside case by type #19347

pavel-odintsov opened this issue Mar 1, 2017 · 4 comments

Comments

@pavel-odintsov
Copy link

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

Latest from play.golang.org

What operating system and processor architecture are you using (go env)?

Mac OS

What did you do?

I do comparison of uint value inside switch by type.

And I got different result for same code:
https://play.golang.org/p/MGQjG9ij4y and https://play.golang.org/p/kUgwdQrOe5

What did you expect to see?

I expect same result from both commands.

What did you see instead?

I see different results.

I think that compiler should notify me about this issue or restrict it completely because it's very unexpected behaviour from code.

@josharian
Copy link
Contributor

It is a bit confusing, but the compiler is doing the right thing here. In the first code snippet, value == 0 is false because value has concrete type uint, but 0 has type int. For interfaces to compare equal, both their type and their concrete value must be the same.

Two other ways to write this program to avoid this problem:

I think in general you probably want to use the second form.

@pavel-odintsov
Copy link
Author

Thanks you for explanation! But I still think that at least go vet should notify about this pitfall.

@griesemer
Copy link
Contributor

The more common way to write such a switch is to introduce a variable with the type switch: https://play.golang.org/p/93shxyhA_Z and then the code is less surprising.

@pavel-odintsov
Copy link
Author

pavel-odintsov commented Mar 2, 2017

@griesemer thank you for advice! It's definitely good advice to avoid such cases!

@golang golang locked and limited conversation to collaborators Nov 9, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants